BFS and DFS are two algorithms for traversing graphs. BFS uses a queue and visits the neighbor nodes level by level starting from the source node. DFS uses a stack and visits nodes by going deeper first, exploring each branch as far as possible before backtracking. Some applications of BFS include computing distances and checking for cycles. Applications of DFS include checking for biconnected graphs.
INTRODUCTION
Graph traversal isalso known as graph search refers to the
process of visiting each vertex in a graph.
Such traversals are classified by the order in which the
vertices are visited. Tree traversal is a special case of graph
traversal.
4.
DEPTH FIRST SEARCH
Depth-firstsearch (DFS) is an algorithm for traversing
or searching tree or graph data structures.
DFS uses stack.
5.
Depth-First Search
// recursive,preorder
void dfs (Node v) {
if (v == null)
return;
if (v not yet visited)
visit&mark(v); // visit node before adjacent nodes
for (each w adjacent to v)
if (w has not yet been visited)
dfs(w);
} // dfs
BREADTH FIRST SEARCH
Breadth-firstsearch (BFS) is an algorithm for traversing or
searching tree or graph data structures.
It uses queue.
24.
Breadth-First Search
// non-recursive,preorder, breadth-first search
void bfs (Node v) {
if (v == null)
return;
enqueue(v);
while (queue is not empty) {
dequeue(v);
if (v has not yet been visited)
mark&visit(v);
for (each w adjacent to v)
if (w has not yet been visited && has not been queued)
enqueue(w);
} // while
} // bfs
Applications of BFS
•
•
•
ComputingDistances
Checking for cycles in a graph
Reachability: Given a graph G and vertices x and y, determine if there
exists a path from x to y.
37.
Applications of DFS
•Checking for Biconnected Graph: A graph is biconnected if removal of
any vertex does not affect connectivity of the other vertices. Used to
test if network is robust to failure of certain nodes. A single DFS
traversal algorithm.