Professional Documents
Culture Documents
16 Graphs2
16 Graphs2
2
2
v1 v2
4 1 3 10
2 2
v3 v4 v5
8 4
6
5
1
v6 v7
3
2
v1 v2
4 1 3 10
2 2
v3 v4 v5
8 4
6
5
1
v6 v7
4
5
6
7
8
9
Worst-case:
O(|E| log|E|)
10
11
12
1
13
1
14
1
15
1
4 5
16
1
4 5 6
17
1
2 7
4 5 6
18
1
2 7
3 8
4 5 6
19
1
2 7
3 8
4 5 6 9
20
1
2 7
3 8
4 5 6 9 10
21
1
2 7
3 8 11 16
4 5 6 9 10 12 13 14 15 17
22
1
2 7
3 8 11 16
4 5 6 9 10 12 13 14 15 17
23
1
2 7
3 8 11 16
4 5 6 9 10 12 13 14 15 17
24
(only when you can’t go any deeper)
Print Root
Visit Child1,Child2...Child2
1
Almost like preorder traversal
2 7
3 8 11 16
4 5 6 9 10 12 13 14 15 17
25
(only when you can’t go any deeper)
a
b d
c e f
26
•“Do-something” at the visited node
a(1)
b d
c e f
27
•Visit any unvisited adjacent nodes
a(1)
b(2) d
c e f
28
•Visit any unvisited adjacent nodes
a(1)
b(2) d
c(3) e f
29
•Visit any unvisited adjacent nodes
a(1)
b(2) d
c(3) e f
30
•Visit any unvisited adjacent nodes
a(1)
b(2) d(4)
c(3) e f
31
•Visit any unvisited adjacent nodes
a(1)
b(2) d(4)
c(3) e f
32
•Visit any unvisited adjacent nodes
a(1)
b(2) d(4)
c(3) e(5) f
33
•Visit any unvisited adjacent nodes
a(1)
b(2) d(4)
34
35
dfs (Vertex v)
{ a(1)
v.visited = true;
for each w adjacent to v
if ( !w.visited )
dfs (w);
b d
}
c e f
36
dfs (Vertex v) dfs (a) will call
{ a(1)
v.visited = true; dfs(b) and then dfs (d)
for each w adjacent to v
if ( !w.visited )
b d
dfs (w);
}
c e f
37
a(1)
c e f
38
a(1)
b(2) d
dfs(c) will NOT
call dfs(b)
because b
is already
visited c(3) e f
39
dfs(d) will NOT call
a(1)
dfs(c)
dfs(f)
c(3) e f
40
a(1) dfs(e)
will not call
dfs(c)
b(2) d (4)
and just return
c(3) e(5) f
41
a(1) dfs(f) will NOT call
dfs(c) and
will just return
b(2) d (4)
42
dfs (a) was supposed to call
a(1)
dfs(b) and then dfs (d)
b(2) d (4)
43
dfs (a) was supposed to call
a(1)
dfs(b) and then dfs (d)
44
a(1)
b(2) d (4)
47
dfs (Vertex v)
{
v.visited = true;
for each w adjacent to v
if ( ! w.visited )
dfs (w);
}
O(1 |E| )
u
u
48
// If the graph is NOT connected
dfsALL (Graph g)
{
for each v in g
if ( ! v.visited )
dfs(v);
}
49
DFS partitions the arcs of a directed graph into Tree,
Forward, Backward, and Cross arcs
a(1)
b(2) d (4)
50
Tree Arcs
u→ v
a(1)
such that dfs (v) is
called by dfs(u)
b(2) d (4)
That is, tree arcs are
those arcs that form the
DFS tree.
c(3) e(5) f(6)
51
Forward arcs
a(1)
u→v
v is a proper
descendant of u,
b(2) d (4)
but not a child of u
in the DFS tree
52
Backward arcs
a(1)
u→ v
53
Cross arcs
a(1)
u→v
b(2) d (4) v is neither an
ancestor nor a
descendant of u
in the DFS tree.
c(3) e(5) f(6)
54
Cross arcs
a(1)
u→v
b(2) d (4)
v is neither an
ancestor nor a
descendant of u
c(3) e(5) f(6) in the DFS tree.
a(1)
b(2) d (4) 4
1 2
58
6
a(1)
b(2) d (4) 4
59
6
a(1)
b(2) d (4) 4
60
6
a(1)
b(2) d (4) 4
61
62
63
64
65
66