CS 332: Algorithms: All00/lecture18
CS 332: Algorithms: All00/lecture18
Graph Algorithms
https://www.cs.virginia.edu/~luebke/cs332.f
all00/lecture18.ppt
r s t u
v w x y
r s t u
0
v w x y
Q: s
David Luebke 9 10/14/18
Breadth-First Search: Example
r s t u
1 0
1
v w x y
Q: w r
r s t u
1 0 2
1 2
v w x y
Q: r t x
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
David Luebke 16 10/14/18
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: Ø
David Luebke 17 10/14/18
BFS: The Code Again
BFS(G, s) {
initialize vertices; Touch every vertex: O(V)
Q = {s};
while (Q not empty) {
u = RemoveTop(Q);
for each v u->adj { u = every vertex, but only once
if (v->color == WHITE) (Why?)
v->color = GREY;
So v = every vertexv->d = u->d + 1;
that appears in v->p = u;
Enqueue(Q, v);
some other} vert’s
adjacencyu->color
list = BLACK;
}
} What will be the running time?
Total running time: O(V+E)
| |
| | |
2 | |
| | |
2 | |
3 | | |
2 | |
3 | 4 | |
2 | |
3 | 4 5 | |
2 | |
3 | 4 5 | 6 |
2 | 7 |
3 | 4 5 | 6 |
2 | 7 |
3 | 4 5 | 6 |
2 | 7 9 |
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 14|
2 | 7 9 |10
3 | 4 5 | 6 14|15
2 | 7 9 |10
3 | 4 5 | 6 14|15