简体   繁体   中英

Check if directed graph is strongly connected using adjacency list

I need to find out if given adjacency list (int[][]) is describing a strongly connected graph. I am failing a few test cases with more than 2 nodes in the graph. for example adjlist = new int[][] {{ 1 },{ 2 },{ 0 },}; meaning that node 0 (first in list) can connect to node 1, node 1 can connect to node 2, and node 2 can connect to node 0. I tried this:

 public boolean allDevicesConnected(int[][] adjlist) {
     Boolean[] visited = new Boolean[adjlist.length];
     for (int i = 0; i < adjlist.length; i++) {
         for (int b = 0; b < visited.length; b++) {
             visited[b] = false;
         }
         DFS1( adjlist, i, visited);
     }
        for (int j = 0; j < visited.length; j++) {
            if (visited[j] == false) {
                return false;
         }
     }   
     return true;
}
 
 private static void DFS1(int[][] adjlist, int v, Boolean[] visited) {
    visited[v] = true;
    for (int i = 0; i < adjlist[v].length; i++) {
        if (visited[i] == false) {
            DFS1(adjlist, i, visited);
        }
    }
}

any help would be great thanks!!

Your idea to use a depth first search, while marking nodes as visited to determine if strongly connected is a good idea.

The first double for loop is not needed. If the graph is actually strongly connected, it does not matter at which node we start at.

Firstly, I notice that you are doing this in your DFS search:

visited[i] == false

and

DFS1(adjlist, i, visited);

That said, when you did this you are not checking the right node. You should be checking not the index i, but rather the actual value of the node stored at index i.

I edited your code to use this idea:

public boolean allDevicesConnected(int[][] adjlist){
    boolean[] marked = new boolean[adjlist.length];  // Default is set to false  

    DFS_helper(0, adjlist, marked);

    for(boolean b : marked)
        if(b == false) return false;

    return true;
}

public void DFS_helper(int node, int[][] adjlist, boolean[] marked){
    marked[node] = true;

    for (int i = 0; i < adjList[node].length; i++) {
        int dest = adjlist[node][i];
        if(marked[dest] == false)
            DFS_helper(dest, adjlist, marked);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM