Lec 35graph
Lec 35graph
algorithm.
Try to color as many vertices as possible with the first
color, and then as many uncolored vertices with the
second color, and so on.
The approach would be:
1. Select some uncolored vertex, and color with new color.
2. Scan the list of uncolored vertices. For each uncolored
vertex, determine whether it has an edge to any vertex
already colored with the new color. If there is no such
edge, color the present vertices with the new color.
1
This is called “greedy”, because it colors a vertex,
whenever it can, without considering potential
drawbacks.
3
1 5 2
3
4
1 5 2
4
2
Graph Searching
Given: a graph G = (V, E), directed or undirected
Goal: methodically explore every vertex and
every edge
Ultimately: build a tree on the graph
Picka vertex as the root
Choose certain edges to produce a tree
Note: might also build a forest if graph is not
connected
3
Breadth-First Search
Given a G=(V,E) and distinguished source vertex s,
BFS systematically explores the edges of G to
“discover” every vertex reachable from s.
Creates a BFS tree rooted at s that contains all such
vertices.
Expands the frontier between discovered and
undiscovered vertices uniformly across the breadth of
the frontier.
The algorithm discovers all vertices at distance k from s
before discovering any vertices at distance k+1
4
Breadth-First Search
will associate vertex “colors” to guide the algorithm
White vertices have not been discovered
All vertices start out white
Grey vertices are discovered but not fully explored
They may be adjacent to white vertices and represent the
frontier between the discovered and the undiscovered.
Black vertices are discovered and fully explored
They are adjacent only to black and gray vertices
Explore vertices by scanning adjacency list of grey
vertices
5
Breadth-First Search
BFS(G, s) {
initialize vertices;
Q = {s}; // Q is a queue initialize to s
while (Q not empty) {
u = Dequeue(Q);
for each v u->adj {
if (v->color == WHITE){
v->color = GREY;
v->d = u->d + 1;
v->p = u;
Enqueue(Q, v);
}
} What does v->d represent?
u->color = BLACK;
}
What does v->p represent?
}
6
Breadth-First Search: Example
r s t u
v w x y
7
Breadth-First Search: Example
r s t u
0
v w x y
Q: s
8