Depth First Search
Back to cs141 |
The purpose of Depth First Search (DFS), like Breadth First Search, is to visit every node of a graph and collect some sort of information about how that node was discovered. Like BFS, DFS can be used on both undirected and directed graphs. What makes DFS different from BFS is both the method used to discover the nodes, and the information recorded about that node. Instead of radiating outward from the source node (as in BFS), a DFS explores a single route at a time. Once a "path" has been fully discovered, DFS backtracks and searches another path. This process is continued until all possible paths have been exhausted.
The information recorded by DFS, is the "time" at which the node was first visited and last visited. This information can then be used various applications.
To implement a Depth First Search, a few additional data structures are needed:
The code for doing a DFS can be a bit tricky to understand because it uses recursion.
The pseudo-code for DFS:
The following is an example of DFS on a directed graph with ( c ) as the source vertex. The letter next to each vertex represent the name of that vertex, the text inside the vertex correspond to the first and last visit time in the form (first/last). The path taken by DFS is shown with red arrows, and the edge currently being explored is shown with a blue arrow. The parent information is not included.