Depth-First Search (DFS) is an aggressive graph traversal algorithm. Unlike BFS which explores the graph layer by layer, DFS dives as deep as possible down a single path until it hits a dead end. Only then does it backtrack to explore other paths.
You can think of DFS as navigating a complex maze. Here is how it operates:
stack.visited.
Below is the Python implementation used in our animation engine. Notice how the
stack uses the pop() method to pull from the end of the list,
creating the LIFO behavior.
def dfs(start_node):
stack = [start_node]
visited = []
visit(start_node, f"Starting DFS from node {start_node}")
while len(stack) > 0:
# Pop from the end of the list (Stack behavior)
current = stack.pop()
if current not in visited:
visited.append(current)
visit(current, f"Diving into node {current}")
# Reverse neighbors to explore the first added neighbor first
for neighbor in reversed(neighbors(current)):
if neighbor not in visited:
stack.append(neighbor)
select(neighbor)
# Run the algorithm
dfs("1")
Just like BFS, DFS is highly efficient and will visit every connected component of the graph exactly once.
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(V + E)$ | Where $V$ is the number of vertices and $E$ is the number of edges. Every vertex and edge is explored exactly once in the worst-case scenario. |
| Space Complexity | $O(V)$ |
The algorithm requires extra memory for the stack and the
visited list. In the worst-case scenario (e.g., a straight line of
nodes), the stack will hold all vertices at once.
|