java中现在有n个城市,城市之间有坐火车达到,但是城市之间的铁路是有方向的,即:[1,2]表示只可以从1到达2, 给定以下城市间的铁路路线设计,请求出给定城市0到城市(n-1)之间的所有路径 示例1: 输入: [[0,1],[0,2],[1,3],[2,3]] 输出: [0,1,3],[0,2,3]
时间: 2023-12-30 20:02:02 浏览: 27
好的,那么这里给出 Java 语言的解法,同样采用深度优先搜索(DFS)算法:
```java
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(graph, 0, path, res);
return res;
}
private void dfs(int[][] graph, int cur, List<Integer> path, List<List<Integer>> res) {
path.add(cur);
if (cur == graph.length - 1) {
res.add(new ArrayList<>(path));
} else {
for (int next : graph[cur]) {
dfs(graph, next, path, res);
}
}
path.remove(path.size() - 1);
}
}
```
其中,函数 `allPathsSourceTarget` 接收一个邻接表 `graph` 作为输入,返回一个包含所有从节点 `0` 到节点 `n-1` 的路径的列表。我们首先定义一个空的列表 `res` 和路径列表 `path`,然后调用 `dfs` 函数开始搜索。在 `dfs` 函数中,我们首先将当前节点 `cur` 添加到路径列表 `path` 中,如果当前节点是目标节点 `n-1`,则将当前路径添加到结果列表 `res` 中。否则,我们遍历当前节点能够到达的所有节点,并递归搜索它们。最后,我们将当前节点从路径列表 `path` 中移除,以便搜索其他路径。