前言
今天的题目注意的是需要找到所有可能的路径,不能找到就返回。使用bfs搜索。答案在注释中
题目
源码
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> ans=new ArrayList<>();
if (graph.length==0){//空则返回
return ans;
}
bfs(graph,0,new ArrayList<Integer>(),ans);
return ans;
}
public void bfs(int[][]graph,int cur,List<Integer> list,List<List<Integer>> ans){
list.add(cur);//cur为当前节点
if(cur==graph.length-1){//当当前节点到达终点时,将路径添加到结尾
ans.add(new ArrayList<>(list));
}
for(int i :graph[cur]){//递归遍历每个节点
bfs(graph,i,list,ans);
}
list.remove(list.size()-1);
}
}