BFS Master
BFS Master
Neelima Gupta
[email protected]
Graph Traversals
Breadth First Search
u1
u2 u3
u4 u6
u5
i
Implementation of BFS
BFS(G, s)
For j=1..n { color[j] = white; level[j] = ∞; parent[j] = null; } //Initialization
Enqueue(Q, s)
color[s] = grey; // Vertex added in the queue
level[s] = 0; white : not yet reached
Q = ∅;
grey: waiting in the queue
While Q ≠ ∅ to be visited
i = Dequeue(Q);
process(i); //for eg. update the weather profile of cityblack:
i visited
u1
u2 u3
u4 u6
u5
Tree Edge: (u,v) is a tree edge if ‘v’ is visited first time from ‘u’. ‘u’ is called
the parent of ‘v’ and ‘v’ is a child of ‘u’.
Red Edges: Tree Edges
i
Cross Edges
• Ancestor(u): Ancestor of a vertex ‘u’ is a vertex that lies
on a path from the root to ‘u’ (including ‘u’ and the root).
• Descendant(u): Descendant of a vertex ‘u’ is a vertex that
lies on a path from ‘u’ to a leaf (including ‘u’ and the
leaf).
• Cross Edge: (u,v) is a cross edge if neither ‘v’ is a
descendant of ‘u’ nor ‘u’ is a descendant of ‘v’.
Breadth First Search
(Undirected Graph)
u1
u2 u3
u4 u6
u5
Green Edges: Cross Edges
Can we have a (u, v) edge with ‘u’ as an ancestor/descendant of ‘v’ other
than the tree edge?
i
Breadth First Search
(Directed Graph)
u1
u2 u3
u4 u6
u5
i
Breadth First Search
(Directed Graph)
u1
u2 u3
u4 u6
u5
u1
u2 u3
u4 u6
u5
u1
u2 u3
u4 u6
u5
u2 u3
u4 u6
u5
i
Applications of BFS: Checking Bipartiteness
u2 u3
u4 u6
u5
i
Applications of BFS: Checking Bipartiteness