Transcript here

CMSC 341
Graphs – DFS Expanded
Depth First Traversal with Finish Times
dfs(Graph G) {
for (each v  V)
d[v] = 0
time = 0
for (each v  V)
if (d[v] = 0)
dfs (v)
}
dfs(Vertex v) {
time = time + 1
d[v] = time
for(each vertex w adjacent
if (d[w] = 0)
dfs(w)
time = time + 1
f[v] = time
}
// d = discovery “time”
// “global” variable
// not discovered yet
// “discover” and mark v
from v)
// w not discovered
// v is “finished”
2
Edge Types
After DFS, edges can be classified into the following types:
– tree edges -- a discovered vertex v1 encounters an
undiscovered vertex v2; the edge between them is a tree
edge
– back edges -- a discovered vertex v1 encounters a
discovered but unfinished vertex v2; the edge between
them is a back edge. (Graph has a cycle if and only if
there is a back edge.)
– forward edges (directed graphs only) -- a discovered
vertex v1 encounters a finished vertex v2
– cross edges (directed graphs only) -- a discovered
vertex v1 encounters a finished vertex v2 and d[v1] >
d[v2]
3
Edge Types (after DFS completion)
Condition
If (d[v1] < d[v2])
&& (f[v1] > f[v2])
Type of Edge (v1, v2)
Tree
Else if (d[v1] > d[v2])
&& (f[v1] < f[v2])
Back
Else if (d[v1] > d[v2])
&& (f[v1] > f[v2])
Cross
Else (d[v1] < d[v2]-1)
&& (f[v1] > f[v2])
Forward
4
Utility of Discovery/Finish Times
• A graph contains a cycle if and only if it contains a back
edge.
• Finish times can be used to do a topological sort of a
digraph (later).
• Finish times can be used to find strongly connected
components in a graph.
5