VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-we-can-visit-all-other-nodes-from-any-node-in-given-directed-graph/

⇱ Check if we can visit all other nodes from any node in given Directed Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if we can visit all other nodes from any node in given Directed Graph

Last Updated : 23 Jul, 2025

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 0

Input: N = 3, edges[] = {{1, 0}};
Output: False

An approach using Kosaraju's algorithm:

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:

  • Create adjacency list adj1 for storing the graph.
  • Do DFS in random order of vertices and store the visited vertices in a stack stk while backtracking.
  • Reverse the direction of all edges of the adj1 graph and store the newly created graph in adj2.
  • Do dfs2 in order of stack and keep count of the strongly connected components in variable scc.
  • Check the count of scc:
    • If the count of scc is greater than 1, return false.
    • Otherwise, return true.

Below is the implementation of the above approach:


Output
True

Time Complexity: O(N+E), where E is the number of edges
Auxiliary Space: O(N+E)

Comment
Article Tags: