当前位置:网站首页>2022.07.14_每日一题
2022.07.14_每日一题
2022-07-31 06:07:00 【诺.い】
797. 所有可能的路径
题目描述
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。
示例 1:

输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:

输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
提示:
n == graph.length2 <= n <= 150 <= graph[i][j] < ngraph[i][j] != i(即不存在自环)graph[i]中的所有元素 互不相同- 保证输入为 有向无环图(DAG)
- 深度优先搜索
- 广度优先搜索
- 图
- 回溯
coding
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
int index = 0;
List<Integer> record = new ArrayList<>();
// 从 0 出发
record.add(0);
dfs(graph, res, index, record);
return res;
}
private void dfs(int[][] graph, List<List<Integer>> res, int index, List<Integer> record) {
// 到 n - 1 over
if (index == graph.length - 1) {
// 将当前记录的路径添加至 res
res.add(new ArrayList<>(record));
return;
}
for (int i = 0; i < graph[index].length; i++) {
// 添加下一个指针指向节点
record.add(graph[index][i]);
// 把当前添加的节点当作下一节点的索引位置, 从下一节点开始继续 dfs
dfs(graph, res, graph[index][i], record);
// 回溯
// 【PS】: list.remove(int 索引)
// list.remove(new Integer(list 集合中的元素))
record.remove(new Integer(graph[index][i]));
}
}
}
边栏推荐
猜你喜欢
随机推荐
HuffmanTree
Database Principles Homework 3 — JMU
opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
Third-party library-store
高并发与多线程之间的难点对比(容易混淆)
《白帽子说Web安全》思维导图
Install the gstreamer development dependency library to the project sysroot directory
Install and use uView
MySql的安装配置超详细教程与简单的建库建表方法
服务器和客户端信息的获取
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism
360 push-360 push tool-360 batch push tool
Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
[PSQL] 复杂查询
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
Detailed explanation of js prototype
[PSQL] SQL基础教程读书笔记(Chapter1-4)
nohup原理
R——避免使用 col=0









