简体   繁体   中英

Correct Implementation to find Bridges in graph

I have following implementation to find Cut Edge/ Bridges in a graph :

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class TarjanCutEdge {

    public static void main(String[] args) {
        Graph g = new Graph(8);
        g.addEdge(0,1);
        g.addEdge(1,2);
        g.addEdge(2,0);
        g.addEdge(2,3);
        g.addEdge(3,4);
        g.addEdge(4,5);
        g.addEdge(5,6);
        g.addEdge(6,4);
        g.addEdge(6,7);
        g.addEdge(4,7);
        List<Pair<Integer,Integer>> result = new LinkedList<>();
        getCutEdges(g,result);
        System.out.println(result);
    }

    private static void getCutEdges(Graph g, List<Pair<Integer, Integer>> result) {

        int[] disc = new int[g.getNumVertices()];
        int[] low = new int[g.getNumVertices()];
        int[] parent = new int[g.getNumVertices()];
        Arrays.fill(disc,-1);
        Arrays.fill(low,-1);
        Arrays.fill(parent,-1);

        for(int i=0;i<g.getNumVertices();i++){
            if(disc[i] == -1) // unvisited
                dfs(i,g,disc,low,parent,result,0);
        }
    }

    private static void dfs(int u, Graph g, int[] disc, int[] low, int[] parent,
                            List<Pair<Integer, Integer>> result,int time) {
        disc[u] = low[u] = time;
        time++;
        for(int v : g.getVertices(u)){
            if(disc[v] == -1){
                parent[v] = u;
                dfs(v,g,disc,low,parent,result,time);
                low[u] = Math.min(low[u],low[v]);
                if(low[v] > low[u]){ // no back edge present
                    result.add(new Pair<>(u,v));
                }
            }else if(v != parent[u]){ // ignore child to parent edge
                low[u] = Math.min(low[u],disc[v]);
            }
        }
    } 
}

The implementation is working for most test cases except one. That one test case has 1000 nodes and ~56k edges. I am trying to solve this problem - https://leetcode.com/problems/critical-connections-in-a-network/

How can I validate whether it's the code which is wrong or the test case?

Please do have a look at code, if you already know the Tarjan's Algorithm.

It was a coding mistake, for an edge to be a bridge, we have to check for low of neighbour to discovery of current node (because we have to check no neighbour 'v' of current node 'u' have a backward edge to any ancestor of 'u', as if that backward is present then the graph will still be connected if the edge between 'u'-'v' is removed):

if(low[v] > disc[u]){ // no back edge present
   result.add(new Pair<>(u,v));
}

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