Learn Graph-Traversal Through Animations
Learn Graph-Traversal Through Animations
on
Graph Traversal
-By Subash Joshi
Introduction
Graph traversal is the process of visiting all the
nodes or vertices of a graph in a systematic way.
It is used for searching a vertex in graph.
Using graph traversal, we visit all vertices of a
graph without getting into looping path.
Types of graph traversal techniques:
BFS (Breadth First Search)
DFS (Depth First Search)
Breadth First Search (BFS)
A B C
D E F
Queue:
Step 1
A B C
D E F
Queue:
A
-Select the vertex A as starting point (visit A)
-Insert A into the Queue.
Step 2
A B C
D E F
Queue:
D E B
-Visit all adjacent vertices of A which are not
visited (D,E,B)
-Insert these vertices to queue and delete A from queue.
Step 3
A B C
D E F
Queue:
E B
-Visit all adjacent vertices of D which are not
visited (no such vertex)
-delete D from queue.
Step 4
A B C
D E F
Queue:
B C F
-Visit all adjacent vertices of E which are not
visited (C, F)
-Insert these vertices to queue and delete E from queue.
Step 5
A B C
D E F
Queue:
C F
-Visit all adjacent vertices of B which are not
visited (no such vertices)
-Delete B from queue.
Step 6
A B C
D E F
Queue:
F G
-Visit all adjacent vertices of C which are not
visited (G)
-Insert these vertices to queue and delete C from queue.
Step 7
A B C
D E F
Queue:
G
-Visit all adjacent vertices of F which are not
visited (no such vertices)
-Delete F from queue.
Step 8
A B C
D E F
Queue:
A B C
D E F
Depth First Search (DFS)
A B C
D E F
Stack:
Step 1
A B C
D E F
Stack:
A
-Select the vertex A as starting point (visit A)
-Push A into the Stack.
Step 2
A B C
D E F
Stack:
A B
-Visit any adjacent vertices of A which is not
visited (B)
-Push B onto the Stack.
Step 3
A B C
D E F
Stack:
A B C
-Visit any adjacent vertices of B which is not
visited (C)
-Push C onto the Stack.
Step 4
A B C
D E F
Stack :
A B C E
-Visit any adjacent vertices of C which is not
visited (E)
-Push E onto the Stack.
Step 5
A B C
D E F
Stack :
A B C E D
-Visit any adjacent vertices of E which is not
visited (D)
-Push D onto the Stack.
Step 6
A B C
D E F
Stack :
A B C E
-There is no new node from D. So use backtrack.
-Pop D onto the Stack.
Step 7
A B C
D E F
Stack :
A B C E F
-Visit any adjacent vertices of E which is not
visited (F)
-Push F onto the Stack.
Step 8
A B C
D E F
Stack :
A B C E F G
-Visit any adjacent vertices of F which is not
visited (G)
-Push G onto the Stack.
Step 9
A B C
D E F
Stack :
A B C E F
-There is no new node from G. So use backtrack.
-Pop G from the Stack.
Step 10
A B C
D E F
Stack :
A B C E
-There is no new node from F. So use backtrack.
-Pop F from the Stack.
Step 11
A B C
D E F
Stack :
A B C
-There is no new node from E. So use backtrack.
-Pop E from the Stack.
Step 12
A B C
D E F
Stack :
A B
-There is no new node from C. So use backtrack.
-Pop C from the Stack.
Step 13
A B C
D E F
Stack :
A
-There is no new node from B. So use backtrack.
-Pop B from the Stack.
Step 14
A B C
D E F
Stack :
A B C
D E F