How to implement depth first search for graph with a non-recursive approach

前端 未结 13 1802
情话喂你
情话喂你 2020-11-28 22:00

I have spent lots of time on this issue. However, I can only find solutions with non-recursive methods for a tree: Non recursive for tree, or a recursive method for the grap

13条回答
  •  失恋的感觉
    2020-11-28 22:11

    okay. if you are still looking for a java code

    dfs(Vertex start){
        Stack stack = new Stack<>(); // initialize a stack
        List visited = new ArrayList<>();//maintains order of visited nodes
        stack.push(start); // push the start
        while(!stack.isEmpty()){ //check if stack is empty
            Vertex popped = stack.pop(); // pop the top of the stack
            if(!visited.contains(popped)){ //backtrack if the vertex is already visited
                visited.add(popped); //mark it as visited as it is not yet visited
                for(Vertex adjacent: popped.getAdjacents()){ //get the adjacents of the vertex as add them to the stack
                        stack.add(adjacent);
                }
            }
        }
    
        for(Vertex v1 : visited){
            System.out.println(v1.getId());
        }
    }
    

提交回复
热议问题