BFS DFS
BFS DFS
Graph
2 3
2 3
1 2 3 4
4
2 3 4 5 6
3 4 5 6
5 6 7 8
4 5 6 7 8
5 6 7 8
6 7 8
7 8
8 -
2 3 4
3
5 6 7 8 86
75
Order of visit of Nodes using DFS 42
1 2 5 6 3 4 7 8 1
A DFS(A) DFS(B)
Mark A-visited Mark B-visited
1
B C D Adjacent to A Adjacent to B
are B,C,D is E(unvisited)
B,C,D are
E DFS(E)
unvisited.
Order of visit of Nodes using DFS DFS(B)
2
A B E C D DFS(C) 3
DFS(D)
DFS(E)
DFS(D) DFS(C)
4 Mark E-visited
Mark D-visited Mark C-visited
Adjacent to E
Adjacent to D Adjacent to C
is B(visited)
is A(visited) is A(visited)
Return
Return Return
Prepared By: Vaishali Koria Data Structure and Algorithms
Depth First Search(DFS)
Find DFS sequence for following Graph (Start vertex is 0)
2 3
Here, After visiting 2, next node to check is 1 which is already visited, and 1 is not a
parent of 2… So, it can be said that graph contains a cycle.
More formally, For every visited vertex 'v', if there is an adjacent 'u' such that u is
already visited and u is not parent of v, then there is a cycle in graph.