Kosaraju Algo

mail@pastecode.io avatar
unknown
java
15 days ago
2.5 kB
1
Indexable
Never
public static void dfsSCC(int src, ArrayList<Integer>[] graph, boolean[] vis, ArrayList<Integer> order){
        vis[src] = true;

        for(int nbr: graph[src]){
            if(vis[nbr] == false){
                dfsSCC(nbr, graph, vis, order);
            }
        }

        order.add(src);
    }

    public static void dfsSCC2(int src, ArrayList<Integer>[] nGraph, boolean[] vis){
        vis[src] = true;
        System.out.print(src+" ,");

        for(int nbr: nGraph[src]){
            if(vis[nbr] == false){
                dfsSCC2(nbr, nGraph, vis);
            }
        }
    }

    public static int findSCC2(ArrayList<Integer>[] graph, int N){
        boolean[] vis = new boolean[N];

        ArrayList<Integer> order = new ArrayList<>();

        for(int i=0; i<N; i++){
            if(vis[i] == false){
                dfsSCC(i, graph, vis, order);
            }
        }

        // reverse the graph
        ArrayList<Integer>[] nGraph = new ArrayList[N];

        for(int i=0; i<N; i++){
            nGraph[i] = new ArrayList<>();
        }

        for(int u=0; u<N; u++){
            for(int v: graph[u]){
                addEdge(nGraph,v,u);
            }
        }

        vis = new boolean[N];
        int sccomps = 0;
        for(int i=N-1; i>=0; i--){
            int src = order.get(i);

            if(vis[src] == false){
                System.out.print("Starting new component: ");
                dfsSCC2(src, nGraph, vis);
                sccomps++;
                System.out.println();
            }
        }

        return sccomps;
    }















    // construction ===============
    public static void addEdge(ArrayList<Integer>[] graph,int u, int v){
        graph[u].add(v);
        // graph[v].add(u);
    }

    public static void printGraph(ArrayList<Integer>[] graph, int N){
        for(int i=0; i<N; i++){
            System.out.println(i + " -> " + graph[i]);
        }
    }

    public static void main(String[] args){
        int N = 9;
        ArrayList<Integer>[] graph = new ArrayList[N];

        for(int i=0; i<N; i++){
            graph[i] = new ArrayList<>();
        }

        addEdge(graph,0,1);
        addEdge(graph,1,3);
        addEdge(graph,2,0);
        addEdge(graph,3,2);
        addEdge(graph,3,5);
        addEdge(graph,4,6);
        addEdge(graph,6,7);
        addEdge(graph,7,8);
        addEdge(graph,6,5);
        addEdge(graph,5,4);

        System.out.println(findSCC2(graph,N));
    }
Leave a Comment