![]() |
VOOZH | about |
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:
Below is the implementation of the above approach.
2
Time Complexity: O(N+M)
Auxiliary Space: O(N+M)