Depth First Traversal
tags: graph-traversal depth-first-search implicit-graph
Depth first search is a type of graph traversal that begins at a given vertex and recursively explores its neighbors. The time complexity is O(V+E), where V is the number of vertices and E is the number of edges in the graph.
The main application of DFS is to discover all the reachable nodes starting from a given vertex of a graph. DFS is a basic building block for several algorithms such as the detection of biconnected components, topological sort etc.
Recursive Implementation
The node and link class encapsulates the functionality of the Node and Link abstrations in a graph.
|
|
In depth first traversal the current node is first processed. Then the node’s links are recursively processed.
|
|
If the graph contains a cycle, the traverse method will loop forever. There must be a way to tell if a node has been visited before. Add a visited property to the node class.
|
|
Now the current node is marked as visited by setting the visited array to true. Then the node’s links can be processed in the loop. If the node has not been visited before, it is processed in the recursive call.
Alternative Implementation
|
|
The disadvantage of the recursive implementation is that it may lead to very deep levels of recursion. If the number of nodes is large, it can exhaust the program’s stack space and crash the program.
Iterative Implementation
Iterative version of the program can avoid this problem. A stack is used to keep track of the state.
|
|
The start node is first visited and it is pushed onto a stack. Then, as long as the stack is not empty, the next node is retrieved from the stack and it is processed. If a link’s destination node has not been visited, it is marked as visited and added to the stack for later processing.
The graph is traversed in depth-first order. Because the stack returns items in last-in-first-out order, the traversal method moves away from the start node before it gets back to processing that node’s closer neighbors. The traversal visits nodes far away from the start node before it visits all the ones that are closer to the start node, this is called a depth-first traversal.
Alternative Implementation
|
|
Implicit Graph
A grid of dimension i x j is given. Cells that can be visited is marked by the character ‘.’ and cells that cannot be visited is marked by ‘#’. All the neighbor cells of a given cell must be visited. The cells in the boundary have fewer neighbors. The grid itself can be used to mark the visited cells with ‘.’. The recursive traversal is shown below.
|
|