Bfs 2
Bfs 2
Fall 2006
Lecture 23
Graph / Slide 2
initialize
all pred[v] to -1
Record where
you came from
Graph / Slide 4
Visited Table
Adjacency List (T/F)
0 F -
1 F -
0
2 F -
8 3 F -
source 4 F -
2 9 5 F -
1 6 F -
7 F -
3 7 8 F -
6 9 F -
4
5
Pred
Initialize visited
table (all False)
Q ={ } Initialize Pred to -1
Initialize Q to be empty
Graph / Slide 5
1 6 F -
7 F -
3 7 8 F -
6 9 F -
4
5 Pred
Flag that 2 has
been visited.
Q= { 2 }
1 6 F -
7 F -
3 7 8 T 2
6 9 F -
4
5 Pred
Mark neighbors
as visited.
Q = {2} → { 8, 1, 4 }
Record in Pred
Dequeue 2. that we came from
Place all unvisited neighbors of 2 on the queue 2.
Graph / Slide 7
1 6 F -
7 F -
3 7 Neighbors 8 T 2
6 9 T 8
4
5 Pred
Mark new visited
Q = { 8, 1, 4 } → { 1, 4, 0, 9 } Neighbors.
Record in Pred
Dequeue 8. that we came
-- Place all unvisited neighbors of 8 on the queue. from 8.
-- Notice that 2 is not placed on the queue again, it has been visited!
Graph / Slide 8
1 6 F -
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Mark new visited
Neighbors.
Q = { 1, 4, 0, 9 } → { 4, 0, 9, 3, 7 } Record in Pred
that we came
Dequeue 1.
from 1.
-- Place all unvisited neighbors of 1 on the queue.
-- Only nodes 3 and 7 haven’t been visited yet.
Graph / Slide 9
1 6 F -
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Q = { 4, 0, 9, 3, 7 } → { 0, 9, 3, 7 }
Dequeue 4.
-- 4 has no unvisited neighbors!
Graph / Slide 10
1 6 F -
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Q = { 0, 9, 3, 7 } → { 9, 3, 7 }
Dequeue 0.
-- 0 has no unvisited neighbors!
Graph / Slide 11
1 6 F -
7 T 1
3 7 8 T 2
6 Neighbors 9 T 8
4
5 Pred
Q = { 9, 3, 7 } → { 3, 7 }
Dequeue 9.
-- 9 has no unvisited neighbors!
Graph / Slide 12
1 6 T 7
Neighbors 7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Mark new visited
Vertex 6.
Q = { 7, 5 } → { 5, 6 }
Record in Pred
Dequeue 7. that we came
-- place neighbor 6 on the queue. from 7.
Graph / Slide 14
1 6 T 7
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Q = { 5, 6} → { 6 }
Dequeue 5.
-- no unvisited neighbors of 5.
Graph / Slide 15
1 Neighbors 6 T 7
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Q= {6}→{ }
Dequeue 6.
-- no unvisited neighbors of 6.
Graph / Slide 16
1 6 T 7
7 T 1
3 7 8 T 2
6 9 T 8
4
5 Pred
Recursive algorithm
Try some examples, report path from s to v:
Path(0) ->
Path(6) ->
Path(1) ->
The path returned is the shortest from s to v
(minimum number of edges).
Graph / Slide 18
d(v) = ∞;
d(s) = 0;
d(w)=d(v)+1;
Graph / Slide 20