Count of nodes accessible from all other nodes of Graph
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.
Input: N = 5 and M = 5, V = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]
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]]
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.
Time Complexity: O(N+M)
Auxiliary Space: O(N+M)