Академический Документы
Профессиональный Документы
Культура Документы
2. do color[u] WHITE
3. prev[u] NIL x y z
4. time 0
5. for each u V
6. do if color[u] = WHITE
7. then DFS-VISIT(u)
2
DFS-VISIT(u)
1. color[u] GRAY u v w
2. time time+1
3. d[u] time
x y z
4. for each v Adj[u] time = 1
5. do if color[v] = WHITE u v w
1/
6. then prev[v] u
7. DFS-VISIT(v) x y z
8. color[u] BLACK u v w
9. time time + 1
1/ 2/
3/
x y z x y z x y z
u v w u v w u v w
1/ 2/ 1/ 2/ 1/ 2/
B B
4/ 3/ 4/ 3/ 4/5 3/
x y z x y z x y z
u v w u v w u v w
1/ 2/ 1/ 2/7 1/ 2/7
B B F B
4/5 3/6 4/5 3/6 4/5 3/6
x y z x y z x y z
4
Example (cont.)
u v w u v w u v w
1/8 2/7 1/8 2/7 9/ 1/8 2/7 9/
C
F B F B F B
u v w u v w u v w
1/8 2/7 9/ 1/8 2/7 9/ 1/8 2/7 9/
C C C
F B F B F B
B B
4/5 3/6 10/ 4/5 3/6 10/ 4/5 3/6 10/11
x y z x y z x y z
6
Edge Classification
Forward edge (reaches a BLACK u v w
vertex & d[u] < d[v]): 1/ 2/7
F B
Non-tree edges (u, v) that connect a vertex 4/5 3/6
u to a descendant v in a depth first tree x y z
7
Analysis of DFS(V, E)
1. for each u V
2. do color[u] WHITE (V)
3. [u] NIL
4. time 0
5. for each u V (V) exclusive
6. do if color[u] = WHITE of time for
7. then DFS-VISIT(u) DFS-VISIT
8
Analysis of DFS-VISIT(u)
1. color[u] GRAY DFS-VISIT is called exactly
2. time time+1 once for each vertex
3. d[u] time
4. for each v Adj[u]
5. do if color[v] = WHITE Each loop takes
6. then [v] u |Adj[v]|
7. DFS-VISIT(v)
8. color[u] BLACK
9. time time + 1 Total: vV |Adj[v]| + (V) = (V + E)
10. f[u] time (E)
9
Properties of DFS
u = prev[v] DFS-VISIT(v) was
called during a search of us
u v w
adjacency list 1/ 2/
3/
x y z
Vertex v is a descendant of vertex u
in the depth first forest v is
discovered during the time in which
u is gray
10
Parenthesis Theorem
y z s t
In any DFS of a graph G, for 3/6 2/9 1/10 11/16
all u, v, exactly one of the
4/5 7/8 12/13 14/15
following holds: x w v u
1. [d[u], f[u]] and [d[v], f[v]] are
s t
disjoint, and neither of u and v
is a descendant of the other z v u
12
Directed Acyclic Graph
DAG Directed graph with no cycles.
Good for modeling processes and structures that
have a partial order:
a > b and b > c a > c.
But may have a and b such that neither a>b nor b>a.
Can always make a total order (either a>b or
b>a for all a b) from a partial order.
Characterizing a DAG
Lemma 22.11
A directed graph G is acyclic iff a DFS of G yields no back edges.
T T T
v u
A B D
C E
A B C D E
17
Topological Sort (Fig Cormen)
undershorts 11/ 16 17/18 socks TOPOLOGICAL-SORT(V, E)
1. Call DFS(V, E) to compute
12/15
pants shoes 13/14 finishing times f[v] for each
shirt 1/8 vertex v
6/7 belt 2. When each vertex is finished,
watch 9/10
tie
insert it onto the front of a
2/5
linked list
3. Return the linked list of
jacket 3/4
vertices
Running time: (V + E)
18
Solutions
19
Solutions
20
Solutions
21
Next Class
22