Depth-first search
Explore one graph branch at a time and prevent a cycle from repeating your work.
Follow a branch before returning
Visit the start, mark it as seen, and recursively visit one unseen neighbor. That call explores its own neighbors before returning. The call stack holds the path you are exploring. An explicit stack is a useful alternative when input may be deep.
How it works
Choose a neighbor, explore as far as you can, and return to the last place where another branch remains. Mark vertices as visited when exploring a graph with cycles. Otherwise, an edge back to an earlier vertex can send the search around the same loop again.
Check for repeated vertices
Even a single undirected edge points back to the previous vertex. Marking each vertex before exploring its neighbors prevents that return from causing a repeated call. The traversal visits reachable vertices in an order determined by the neighbor order.
Use the right traversal
With adjacency lists, the worst-case time is O(V + E). The seen set and recursive call stack use O(V) additional space. DFS can explore a connected component or help find cycles. When an unweighted shortest route is required, choose BFS instead.
Code example
graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A"], "D": ["B"]}
seen = set()
def visit(vertex):
seen.add(vertex)
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in seen:
visit(neighbor)
visit("A")Check your understanding
List the DFS visit order starting from A. Visit available neighbors in alphabetical order and use undirected edges.
See the example and explanation
- Example 1
- Given
A-B, A-C, B-D - Answer
A, B, D, C - Example 2
- Given
Vertices A, B, C. Edge B-C - Answer
A
For A-B, A-C, and B-D, the first branch goes from A through B to D. It finishes, then exploration returns to A and reaches C. In a disconnected graph the visit stops with A.