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

前端 未结 13 1828
情话喂你
情话喂你 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:20

    The following Java Code will be handy:-

    private void DFS(int v,boolean[] visited){
        visited[v]=true;
        Stack S = new Stack();
        S.push(v);
        while(!S.isEmpty()){
            int v1=S.pop();     
            System.out.println(adjLists.get(v1).name);
            for(Neighbor nbr=adjLists.get(v1).adjList; nbr != null; nbr=nbr.next){
                 if (!visited[nbr.VertexNum]){
                     visited[nbr.VertexNum]=true;
                     S.push(nbr.VertexNum);
                 }
            }
        }
    }
    public void dfs() {
        boolean[] visited = new boolean[adjLists.size()];
        for (int v=0; v < visited.length; v++) {
            if (!visited[v])/*This condition is for Unconnected Vertices*/ {
    
                System.out.println("\nSTARTING AT " + adjLists.get(v).name);
                DFS(v, visited);
            }
        }
    }
    

提交回复
热议问题