当前位置:网站首页>Leetcode 797: all possible paths

Leetcode 797: all possible paths

2022-06-23 05:35:00 Swarford

link

subject :
 Insert picture description here

Java Realization :

class Solution {
    
    List<List<Integer>> r=new LinkedList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
    
        //graph Adjacency table , Each element is an array , There are other vertices connected to this vertex 
        LinkedList<Integer> path=new LinkedList<>(); // polymorphic ,LinkedList Only then removerLast() Method !
        traverse(graph,0,path);
        return r;
    }
        void traverse(int[][]graph,int s,LinkedList<Integer> path){
    
            path.add(s); //  Add start node first 
            // Determine whether the iteration has come to an end , If yes, complete a path 
            int n=graph.length;
            if(s==n-1){
    
                r.add(new LinkedList<>(path));
                path.removeLast();// Recursion completes , remove path Medium element ,
                return;
            }
            //dfs
            for(int k :graph[s]){
    
                traverse(graph,k,path);
            }
            path.removeLast(); // Recursion completes , remove path Medium element ,
        } 
}
原网站

版权声明
本文为[Swarford]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230208016421.html