-4

Question

I have a question about this problem:

Given an directed graph that contains N vertices and M edges, please determine that "there is a path from vertex i to vertex j for all 1 <= i, j <= N".

I want to solve for N <= 500, M <= 250000.
I found the naive pathfinding algorithm with dfs but the time complexity is O(N^2 M), so it is very slow.
Please tell me the efficient algorithm to solve it.

Example

For example, if this graph is given:

Example Graph

The answer is NO because there isn't a path from 4 to 1.

square1001
  • 1,196
  • 7
  • 20

1 Answers1

1

The following algorithm can me implemented with O(N+M) complexity.

  1. Take any vertex u. Use flood fill algorithm to reach other vertices. If any vertex is not reachable, return NOK.

  2. Now do the same, but go to the opposite direction. If any vertex is not reachable, return NOK.

  3. Return OK. (Here we know that there is a path from any vertex v to u because of [2], and there is a path from u to any vertex w because of [1].)

AlexD
  • 30,405
  • 3
  • 66
  • 62