I am confused about this answer. Why can't DFS decide if there is a cycle in a directed graph while visiting each node and each edge at most once? Using the white, gray, black method, one should be able to find a cycle if there is a backward edge.
For an unconnected directed graph, why can't one do the following: run DFS from an arbitrary node v
and visit as many nodes as v
is connected to, then run DFS on another unvisited arbitrary node in the graph, if any, until all nodes are visited?
It seems to me that DFS should be able to find a cycle if it exists in at most o(|V|+|E|)
time. Is this claim in the above mentioned answer wrong?
"It is possible to visit a node multiple times in a DFS without a cycle existing"
Moreover, as this other answer suggest, if a cycle exists, DFS should find it after exploring a maximum of |V|
edges, so the run time is really O(|V|)
.
What am I missing?
Update and conclusions:
Based on Pham Trung's comments, it looks like the "simple DFS" in that answer refers to a DFS starting from one node in a strongly connected graph. As I understand it, for a general case that the graph might be unconnected, the following statements should be true:
- Using DFS and starting from an arbitrary unvisited node in an unconnected graph, it is true that each node might be visited more than once, but using white-gray-black coloring, a cycle -if exists - will be correctly found.
- The run time of such a DFS algorithm is
O(d.|V|+|E|)
, whered
is the max in-degree among all nodes (i.e. the max time that we can visit each node using such DFS-based algorithm) - Moreover, as this other answer suggest, if after exploring
O(|V|)
edges, a cycle was not found, it does not exist. So the runtime is reallyO(|V|)
.