所有可能路径
所有可能的路径
题目描述
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。
输入输出样例
样例一
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
样例二
输入: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]]
样例三
输入:graph = [[1],[]]
输出:[[0,1]]
样例四
输入:graph = [[1,2,3],[2],[3],[]]
输出:[[0,1,2,3],[0,2,3],[0,3]]
样例五
输入:graph = [[1,3],[2],[3],[]]
输出:[[0,1,2,3],[0,3]]
题目解析
- 本题就是正常的dfs,但是是第一次用python写题,所以记录一下。
- 思路就是:从0号节点开始,一直往深处遍历,直到遍历到n-1号节点。这个遍历的路径就是一条,并且由于不会出现重复路径一次只需要vector容器,不需要查重功能的set容器。
- 但是值得注意的是:在使用python时,往res加入路径需要append(path[:]),而不是单纯的append(path)
题目代码
//C++代码也放出来一手
class Solution {
private:
vector<vector<int>> res;
int n;
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
n=graph.size();
vector<int> path;
path.push_back(0);
dfs(0,graph,path);
return res;
}
void dfs(int start,vector<vector<int>>& graph,vector<int> &path){
int len=graph[start].size();
if(start==n-1)
res.push_back(path);
else if(len>0) {
for(int i=0;i<len;i++){
path.push_back(graph[start][i]);
dfs(graph[start][i],graph,path);
path.pop_back();
}
}
}
};
#这是python代码
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
res=list()
path=[0]
def dfs(start:int):
if start==len(graph)-1:
res.append(path[:])#十分要注意这个!!!
else:
for i in graph[start]:
path.append(i)
dfs(i)
path.pop()
dfs(0)
return res

浙公网安备 33010602011771号