![]() |
VOOZH | about |
Given N nodes, where each of them is numbered from 0 to N - 1, and array edges, where there is a directed edge from edges[i][0] to edges[i][1], the task is to find whether we can travel from any node to all other nodes or not.
Examples:
Input: N = 2, edges[] = {{0, 1}, {1, 0}};
Output: True
Explanation: We can go to node 0 from 1 and node 1 from 0Input: N = 3, edges[] = {{1, 0}};
Output: False
An idea of solving this problem is to think in terms of finding strongly connected component (SCC) for directed graph, We know that a directed graph is strongly connected if there is a path between all pairs of vertices.
So if there is only a single SCC then only we can visit all the nodes from any other node. The number of SCC can be found using Kosaraju's algorithm.
Follow the steps below to implement the above idea:
Below is the implementation of the above approach:
True
Time Complexity: O(N+E), where E is the number of edges
Auxiliary Space: O(N+E)