The following algorithm can me implemented with O(N+M)
complexity.
-
Take any vertex
u
. Use flood fill algorithm to reach other vertices. If any vertex is not reachable, returnNOK
. -
Now do the same, but go to the opposite direction. If any vertex is not reachable, return
NOK
. -
Return
OK
. (Here we know that there is a path from any vertexv
tou
because of [2], and there is a path fromu
to any vertexw
because of [1].)
solved Determine if there is a path between all vertex pairs on an directed graph