当前位置:网站首页>2022.07.14_Daily Question
2022.07.14_Daily Question
2022-07-31 07:39:00 【No. い】
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) {
// The current record is added to the path of res
res.add(new ArrayList<>(record));
return;
}
for (int i = 0; i < graph[index].length; i++) {
// Add a pointer to the node under
record.add(graph[index][i]);
// Add the current node as the index of the next node location, Starting from the next node to continue dfs
dfs(graph, res, graph[index][i], record);
// 回溯
// 【PS】: list.remove(int 索引)
// list.remove(new Integer(list 集合中的元素))
record.remove(new Integer(graph[index][i]));
}
}
}
边栏推荐
猜你喜欢

剑指offer(一)

Titanic 预测问题

简单谈谈Feign
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?

Obtaining server and client information

基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例

双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分

DirectExchange switch simple introduction demo

2022.07.13_每日一题

【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
随机推荐
360 push-360 push tool-360 batch push tool
【微服务】(十六)—— 分布式事务Seata
【微服务】 微服务学习笔记二:Eureka注册中心的介绍及搭建
iOS大厂面试查漏补缺
【愚公系列】2022年07月 Go教学课程 022-Go容器之字典
【面试:并发篇37:多线程:线程池】自定义线程池
2022.07.14_每日一题
DirectExchange交换机简单入门demo
DAY18:XSS 漏洞
Some derivation formulas for machine learning backpropagation
2022.7.29 Array
【第四章】详解Feign的实现原理
Kubernetes scheduling
Moment.js common methods
Third-party library-store
2022.07.14_每日一题
2022.07.18_每日一题
【并发编程】ReentrantLock的lock()方法源码分析
单点登录 思维导图
深度学习通信领域相关经典论文、数据集整理分享