Graph Traversal: Bfs & Dfs
Graph Traversal: Bfs & Dfs
2
3
8
1
4
5
9
10
6
7 11
Graph Search Methods
(traversal)
• A search method starts at a given vertex v and
visits/labels/marks every vertex that is reachable
from v.
2
3
8
1
4
5
9
10
6
7 11
Graph Search Methods
• Many graph problems solved using a search
method.
▪ Finding Path(shortest) from one vertex to another.
▪ Check if the graph is connected?
▪ Find a (minimum) spanning tree.
• Commonly used search (traversal) methods:
▪ Breadth-first search.
▪ Depth-first search.
Breadth-First Search
• Visit start vertex (selected by user) and put into
a FIFO queue.
• Repeatedly remove a vertex from the queue, visit
its unvisited adjacent vertices, put newly visited
vertices into the queue.
• BFS(G,1)
2
3
4
5
Breadth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 1
4
5
9
10 Blue vertex is
visited
6
7 11
2
3
FIFO Queue
8 2 4
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 2 4
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 4 3 5 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 43 5 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 356
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 356
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 679
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 79
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 9
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 8
4
5
9
10
6
7 11
2
3
FIFO Queue
8 8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1
4
5
9
10
6
7 11
• 4
• 5
• 9
• 1
0
• 6
• 7 • 11
Breadth-First Search Property
• 2
• 3
• 8
• 1 • 1
• 4 0
• 5 • 9 • 11
• 6
• 7
Example start at 1
2
3
8
1 10
4
5 9 11
6
7
Example start at 2
• 2
• 3
• 8
• 1 • 1
• 4 0
• 5 • 9 • 11
• 6
• 7
Example start at 2
• 2
• 3
• 8
• 1 • 1
• 4 0
• 5 • 9 • 11
• 6
• 7
Finding a Path From Vertex v To
Vertex u
2
3
8
1
4
5
9
10
6
7 11
Spanning Tree
2
3
8
1
4
5
9
6
7
depthFirstSearch(v)
{
Label vertex v as reached.
for (each unreached vertex u
adjacenct from v)
depthFirstSearch(u);
}
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
Return to
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
Do a
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
4
5
9
10
6
7 11
Return to 1.
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
• 4
• 5
• 9
• 1
0
• 6
• 7 • 11
Depth-First Search Properties
• Same properties with respect to path
finding, connected components, and
spanning trees.
• Edges used to reach unlabeled vertices
define a depth-first spanning tree when the
graph is connected.
• There are problems for which bfs is better
than dfs and vice versa.
Depth-first-search
Graph Algorithms
54
Problem: Laying Telephone Wire
Central office
55
Wiring: Naïve Approach
Central office
Expensive!
56
Wiring: Better Approach
Central office
57