Graph traversal
Graph traversal
DepthFirstSearch(G,n)
Depth First Search {
for i=1 to n do
visited[i]=false
1. Push starting node into the stack for i=1 to n do
if (!visited[i])
2. Pop an element from the stack, if it
DFS(i)
has not been traversed then traverse
}
it. If it has already been traversed
then just ignore it. (visited[i]=true)
DFS(vertex v)
3. Now push all the unvisited adjacent {
nodes of the popped element on to visited[v]=true
the stack. (push if it is already on the for each vertex w adjacent to v do
stack) if(!visited[w])
4. Repeat step 3 and step 4 until stack DFS(w)
is empty }
Step 1
Push node 1 onto the stack
Stack
1
0 1 2 3 4 5
Top
Step 2
Pop node 1 from the stack, traverse it
Visited[1]=true Stack
Now push all the unvisited adjacent vertices 3 2
of node 1 onto the stack 0 1 2 3 4 5
i.e., 2,3
Top
Traversal 1
Step 3
Pop node 2 from the stack, traverse it
Visited[2]=true
Now push all the unvisited adjacent vertices
of node 2 onto the stack Stacks
i.e., 5,4 3 5 4
Traversal 1, 2 0 1 2 3 4 5
Step 4 Top
Step 6 Top
Step 8 Top
Step 10 Top
0 1 2 3 4 5
Top
Step 11
Pop node 5 from the stack, which is already
traversed.
Traversal 1, 2, 4, 8, 5, 6, 3,7
Stacks
3
0 1 2 3 4 5
Step 12 Top
Top=-1
Traversal 1, 2, 4, 8, 5, 6, 3,7
BFS( v)
Breadth First {
u=v
Search visited[v]=true
repeat
1. Insert starting node into the {
queue for all vertices w adjacent from u do
2. Delete front element from the {
if (visited[w] = = false) then
queue and insert all its {
unvisited neighbours into the Add w to q
rear end of the queue, and visited[w] = true
traverse them.(visited=true) }
}
3. Repeat step 2 until queue is If q is empty then return
empty Delete u from q
} until(false )
}
Step 1
• Insert starting node 1 into queue
• Traversed nodes= 1
• Visited[1]=true
1
0 1 2 3 4 5
Step 8
• Delete front element 6 from queue
• It has no unvisited neighbours
8
• Traversed nodes= 1, 2, 4, 5, 3, 7, 6, 8 0 1 2 3 4 5 6 7 8 9
Front=7 Rear= 7
Step 9
• Delete front element 8 from queue and insert
all its unvisited neighbours 9
• Traversed nodes= 1, 2, 4, 5, 3, 7, 6, 8,9
• Visited[9]=true 9
0 1 2 3 4 5 6 7 8 9
Front=8 Rear= 8
Step 10
• Delete front element 9 from queue
• It has no unvisited neighbours
• Traversed nodes= 1, 2, 4, 5, 3, 7, 6, 8, 9 0 1 2 3 4 5 6 7 8 9
• Queue is empty, therefore stop the process Front=8 Rear= 8