Skip to content
Related Articles

Related Articles

Count of nodes accessible from all other nodes of Graph

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 26 May, 2022

Given a directed graph with N nodes and M edges in array V[], the task is to find the number of nodes that are accessible from all other nodes i.e., they have at least one path from all other nodes.

Examples:

Input: N = 5 and M = 5, V = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]
Output: 2
Explanation:
We can look closely after forming graph 
than captain america only can hide in a 
room 3 and 4 because they are the only room 
which have gates through them. So, 
answer is 2.

Input: N = 2, M = 1, V = [[1, 2]]
Output: 1

 

Approach: This problem can be solved using Kosaraju’s Algorithm to find the count of Strongly Connected Components based on the following idea:

All the nodes in a single strongly connected component are reachable from any other node of that component. If each connected component is considered as a node of the graph then there are the following cases:

  • The connected components are disconnected. So, more than one component will have outdegree greater than 0. In this case, no node is reachable from all other nodes.
  • There is only one connected component. This time all the nodes are reachable from all other nodes.
  • There are more than one connected components and only one node has outdegree equal to 0. In this case only that node is reachable from all other nodes. 

Follow the steps mentioned below to implement the above idea:

  • Find all strongly connected components of the given graph
  • Create a new graph in which each strongly connected component is considered as a single node. (let’s say this graph is grrrr)
  • Find number of nodes in grrrr having outdegree ==0 (let this number is x1)
    • If x1 > 1 then answer is 0 because this suggests that some nodes are not reachable from others or some components are disconnected.
    • If x1 = 0 then answer is also 0.
    • So  exist only when x1 = 1 and the answer is equal to the number of nodes in the strongly connected component having outdegree = 0 in graph grrrr.

Below is the implementation of the above approach.

Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to form the components
    private static void
    dfs(int node, ArrayList<ArrayList<Integer> > adj,
        Stack<Integer> st, int[] vis)
    {
        vis[node] = 1;
        for (Integer it : adj.get(node)) {
            if (vis[it] == 0) {
                dfs(it, adj, st, vis);
            }
        }
        st.push(node);
    }
 
    // Function to run dfs in the
    // transpose adjacency to get
    // the strongly connected components
    private static void
    dfs_(int node, ArrayList<ArrayList<Integer> > transpose,
         int[] vis, int par, int[] parent, int[] no)
    {
        vis[node] = 1;
 
        parent[node] = par;
        no[par]++;
        for (Integer it : transpose.get(node)) {
            if (vis[it] == 0) {
                dfs_(it, transpose, vis, par, parent, no);
            }
        }
    }
 
    // Function to form the new graph using
    // the strongly connected components
    private static void
    dfs__(int node, int[] vis,
          ArrayList<ArrayList<Integer> > adj,
          ArrayList<ArrayList<Integer> > adjn, int[] parent)
    {
        vis[node] = 1;
        for (Integer it : adj.get(node)) {
            int par1 = parent[node];
            int par2 = parent[it];
            if (par1 == par2) {
                continue;
            }
            adjn.get(par1).add(par2);
            if (vis[it] == 0) {
                dfs__(it, vis, adj, adjn, parent);
            }
        }
    }
 
    // Function to find the total number
    // of reachable nodes
    public static int countReachables(int N, int M,
                                      int V[][])
    {
        ArrayList<ArrayList<Integer> > adj
            = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            adj.add(new ArrayList<>());
        }
 
        // Generate the adjacency matrix
        for (int i = 0; i < M; i++) {
            adj.get(V[i][0] - 1).add(V[i][1] - 1);
        }
        int[] vis = new int[N];
 
        // Stack to store the components
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < N; i++) {
            if (vis[i] == 0) {
                dfs(i, adj, st, vis);
            }
        }
        ArrayList<ArrayList<Integer> > transpose
            = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            transpose.add(new ArrayList<>());
            vis[i] = 0;
        }
 
        // Transpose adjacency matrix
        for (int i = 0; i < M; i++) {
            transpose.get(V[i][1] - 1).add(V[i][0] - 1);
        }
        int[] parent = new int[N];
        int par = 0;
        int[] no = new int[N];
        while (!st.isEmpty()) {
            int node = st.pop();
            if (vis[node] == 0) {
                dfs_(node, transpose, vis, par, parent, no);
                par++;
            }
        }
 
        // Adjacency matrix to represent the graph
        // where each node is a strongly connected component
        ArrayList<ArrayList<Integer> > adjn
            = new ArrayList<>();
        for (int i = 0; i < par; i++) {
            adjn.add(new ArrayList<>());
        }
        Arrays.fill(vis, 0);
        for (int i = 0; i < N; i++) {
            if (vis[i] == 0) {
                dfs__(i, vis, adj, adjn, parent);
            }
        }
 
        // Check nodes with outdegree 0
        int outDegree = 0;
        for (int i = 0; i < par; i++) {
            if (adjn.get(i).size() == 0) {
                outDegree++;
            }
        }
 
        // Decide the count based on the conditions
        if (outDegree > 1 || outDegree == 0) {
            return 0;
        }
        else {
            for (int i = 0; i < par; i++) {
                if (adjn.get(i).size() == 0) {
                    return no[i];
                }
            }
        }
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 5;
        int M = 5;
        int V[][] = new int[M + 1][2];
 
        V[0][0] = 1;
        V[0][1] = 2;
        V[1][0] = 2;
        V[1][1] = 3;
        V[2][0] = 3;
        V[2][1] = 4;
        V[3][0] = 4;
        V[3][1] = 3;
        V[4][0] = 5;
        V[4][1] = 4;
 
        // Function call
        int ans = countReachables(N, M, V);
        System.out.println(ans);
    }
}

Output

2

Time Complexity: O(N+M)
Auxiliary Space: O(N+M)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!