In class last time I presented a small undirected graph that defeated Dijkstra and (I claimed) would work with Floyd-Warshall. Unfortunately, the graph contained a negative cycle (a trivial one that got under my radar), hence the shortest-path problem is not well-defined. The fix is to make it a directed graph.
|
| 0 | 1 | 2 | 3 | |
| 0 | 10 | |||
| 1 | 4 | 3 | ||
| 2 | -6 | |||
| 3 | ||||
| 0 | 1 | 2 | 3 | |
| 0 | 10 | 14 | 13 | |
| 1 | 4 | 3 | ||
| 2 | -6 | |||
| 3 | ||||
| 0 | 1 | 2 | 3 | |
| 0 | 10 | 14 | 8 | |
| 1 | 4 | -2 | ||
| 2 | -6 | |||
| 3 | ||||
Graph problems often need to find out whether graph
contains a
cycle. One way to answer this question is to use modify DFS (Readings
388) to see whether our search ever re-visits a vertex. Note that the
modification in the course Readings considers two vertices with an
undirected edge between them to be a cycle. Usually we're interested
only in cycles with 3 or more distinct vertices, so this algorithm
would have to be modified.
This approach runs into problems with a directed graph. Since, in a
directed graph there may be a path from
to
, but not from
to
, the fact that
has already been visited doesn't
necessarily indicate a cycle. Consider the example from Readings
p. 376 (Figure 8.4(b)). Although
has already been visited, and
found all the edges ``downstream'' from it, there is an edge from
to
that the simple DFS modification would flag as a cycle. We
need to set a special value (perhaps
) if a node has been
visited and all nodes reachable from it have been visited.
Another way to do the same thing is to record arrival/departure
numbers.