As its name suggests, is to search deeper into the graph, whenever possible. Given as input graph G = (V, E) and a source vertex S, from where the searching starts. First, we visit the starting node, then we travel through each node along a path, which begins at S. We visit a neighbour vertex of S and again a neighbour of a neighbour of S, and so on.
DFS Through Stack
In this method, a stack is used to keep track of unvisited neighbours of the node. But the question is that how can we distinguish the visited and unvisited nodes? Take another Boolean array VISITED, which will show the visited and unvisited nodes. Let's see the procedure and how it works?
Procedure
1.Push starting node into the stack. 2.Pop an element from the stack, if it has not been traversed then traverse it. If it has already been traversed then just ignore it. after traversing make the value of visited array true for this node. 3.Push all the unvisited adjacent nodes of the popped element on stack. No need to Push the element even if it is already on the stack. 4. Repeat step 2 and 3 until stack is empty.
Let's consider an example to clarify this method which is shown in the following Fig 1.
Fig 1.Suppose, the starting node is 1.
Push(1)
Stack content:1
Pop()
Stack content:empty
visited[1] = TRUEPush all the unvisited adjacent nodes 2, 5, 4 into the stack.
Stack content:2, 5, 4 and Top = 2
Pop()
Stack content:2, 5 and Top = 1
visited[4] = TRUEPush adjacent nodes of 4. But there is no adjacent node.
Stack content:2,5 and Top = 1
Pop()
Stack content:2 and Top = 0
visited[5] = TRUEPush unvisited adjacent nodes of 5.Adjacent node of 5 is 4 which is already visited.
Stack content:2 and Top = 0
Pop()
Stack content:empty and Top = -1
visited[2] = TRUEPush unvisited node of 2.
Stack content:3 and Top = 0
Pop()
Stack content:empty and Top = -1
visited[3] = TRUEStack is empty and there is no adjacent node of 3.So we stop the process.
Finally, the DFS traversal is:
1, 4, 5, 2, 3DFS Using Color Scheme
First, we will see the procedure and then we will understand the method by a suitable example which is shown in Fig 2.
Procedure
DFS(G) for each vertex u &belongs; V[G] do color[u]<-white π[u]<-NIL time<-0 for each vertex u &belongs; V[G] do if color[u]= white then DFS-VISIT(u)
DFS-VISIT(u) color[u]<-gray time<-time+1 d[u]<-time for each v &belongs; Adj[u] do if color[v]=white then π[v]<-v DFS-VISIT(v) color[u]<-black time<-time+1 f(u)<-time
Source code
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.