Depth first traversal.
This algorithm starts its search at the root and explores one of
its children's subtree and then moves on to the next child's
subtree and etcetera
The idea used is to go as deep into the graph as possible and
backtrack once we reach a vertex with unvisited neighbors.
That is, start search at one vertex, after visiting the vertex,
perform dfs for each unvisited adjacent vertex. In this way we
visit all vertices reachable from the starting vertex.
We use a stack data structure.
Algorithm
1. Mark the current node as visited(initially current node is the root node).
2. Check if current node is the end node, If so, then return it.
3. Iterate over children nodes of current node, and do the following:
1. Check if a child node is not visited.
2.If so, then, mark it as visited.
3. Go to it's sub graph recursively until you find the end node(In other words, do the same steps here passing the child node as the current node in the next recursive call).
4. If the child node has the end node in this sub graph, then, return it.
4. If end node is not found, then end node is not in the graph!
Computational complexity
This algorithm takes O(V + E) where v is the number of vertices and e is the number of edges.Applications
- topological sorting.
- bipartite graph testing.
- finding strongly connected components.
- solving puzzles that can only have one solution.
- detecting cycles in a graph.
References
dfs