You are on page 1of 5

Chapter 9 GRAPH

BFS algorithm Its applications

Breadth-first traversal
<void> BFS() Traverses the digraph in breadth-first order
Uses 1. 2.

QueueADT q(), auxiliary function BFSVisit()

q.Create() loop( more vertex v in digraph) 1. color[v] WHITE 2. father[v] null 3. d[v] + 3. time 0 4. loop( more vertex v in digraph) 1. if (color[v]= WHITE) 1. q.Enqueue(v) 2. BFSVisit(v)

5. end BFS

<void> BFSVisit(vertex v) 1. color[v] GRAY 2. d[v] time time +1 3. while( not q.IsEmpty()) 1. v q.QueueFront() 2. loop (more vertex u adjacent to v) 1. if (color[u]= WHITE) 1. color[v] GRAY 2. father[u] v 3. d[u] time time +1 4. q.Enqueue(u) 3. q.DeQueue() 4. color[v] BLACK

end BFSVisit
3

Breadth-first traversal
<void> BFS() <void> BFSVisit(vertex v) 1. color[ v] GRAY Traverses the digraph in breadth-first order
2. d[v] time time +1 Uses QueueADT q(), auxiliary function BFSVisit() 3. while( not q.IsEmpty()) 1. q.QueueFront(v) 1. q.Create() 2. loop (more vertex u adjacent to v) 2. loop( more vertex v in digraph) 1. if (color[u]= WHITE) 1. color[v] WHITE 1. color[u] GRAY 2. father[v] null 2. father[u] v 3. time 0 3. d[u] time time +1 4. loop( more vertex v in digraph) 4. q.Enqueue(u) 1. if (color[v]= WHITE) 3. q.DeQueue() 1. q.Enqueue(v) 4. color[v] BLACK 2. BFSVisit(v) 5. f[v] time time +1 5. end BFS

end BFSVisit
4

How to modify BFS algorithm to


determine in undirected graph
a) cycle ? b) connected components c) bipartite ?

solve some problems in digraph


a) shortest path b) minimum spanning tree/forest (Prims version) c) graph coloring
5

You might also like