Professional Documents
Culture Documents
A,
A,B,
B,E,
E,F,F,H,
H,C,
C,D,
D,GG
7
2
DEPTH-FIRST SEARCH EXAMPLE 3
4
1
6
7
5
0
1, 2, 3, 6, 4, 5, 7, 0
8
DEPTH-FIRST SEARCH
B F
ABFIH
I ABFIHGCD
C G
ABFIHGCDE
A
Starting depth first search at some vertices, we may
D not be able to visit all the vertices.
H
E
A depth-first search, starting at vertex B will visit:
B F I H G C D 9
DEPTH FIRST SEARCH TRAVERSAL
This method visits all the vertices, beginning with a specified start vertex.
This strategy proceeds along a path from vertex V as deeply into the graph
as possible.
This means that after visiting V, the algorithm tries to visit any unvisited
vertex adjacent to V.
When the traversal reaches a vertex which has no adjacent vertex, it back
tracks and visits an unvisited adjacent vertex.
Depth-first traversal makes use of a Stack data structure.
DFS Visited
Array
F C A
A B
C
B D D
H
E
G E F
G
H
A B C
D E F
ABCFED
BFS Traversal
BREADTH-FIRST SEARCH
BFS visits nodes level by level
Start from a given vertex v
Visit all adjacent vertices of v
Visit all adjacent vertices of first adjacent vertex w of v
Then visit all adjacent vertices of second adjacent vertex x of v … etc.
38
BREADTH-FIRST SEARCH2 EXAMPLE
3
4
1
6
7
5
0
1,2,3,7,6,0,5,4
39
BREADTH-FIRST SEARCH
B F
A B D E
I A B D E F
C G A B D E F C H
A A B D E F C H G I
D As was true with depth-first search, a breadth-first
H search from some vertices may fail to locate all the
vertices.
E A breadth-first search from B:
B F G I H C D
40
BREADTH-FIRST GRAPH TRAVERSAL
B D
H
0
G E
Nodes visited: D
BFS
Breadth-first search starts with given
F C node
A Then visits nodes adjacent in some
specified order (e.g., alphabetical)
B D Like ripples in a pond
H
0
G E
Nodes visited: D, C
BFS
Breadth-first search starts with given
F C node
A Then visits nodes adjacent in some
specified order (e.g., alphabetical)
B D Like ripples in a pond
H
0
G E
Nodes visited: D, C, E
BFS
Breadth-first search starts with given
F C node
A Then visits nodes adjacent in some
specified order (e.g., alphabetical)
B D Like ripples in a pond
H
0
G E
Nodes visited: D, C, E, F
BFS
When all nodes in ripple are visited,
F C visit nodes in next ripples
A
B D
H
0
G E
2 1
Nodes visited: D, C, E, F, G
BFS
When all nodes in ripple are visited,
F C visit nodes in next ripples
A
B D
H
0
3 G E
2 1
Nodes visited: D, C, E, F, G, H
BFS
4 When all nodes in ripple are visited,
F C visit nodes in next ripples
A
B D
H
0
3
G E
2 1
Nodes visited: D, C, E, F, G, H, A
BFS
4 When all nodes in ripple are visited,
F C visit nodes in next ripples
A
B D
H
0
3
G E
2 1
Nodes visited: D, C, E, F, G, H, A, B
BFS
F C A
A B
Q
C
B D
D
H
E
G E F
G
H