Summary - DFS
- Algorithms course
- Intermediate
- Lesson 60/80
- 4 min
Run DFS on a graph and print the order in a mini task.
Summary - DFS
DFS dives deep with a stack or recursion and backtracks at dead ends. It is used for pathfinding, cycle detection and topological sort.
In this mini task you will run DFS and print the visit order; combine all steps.
DFS walks deep graphs efficiently; this is why it is preferred for connectivity analysis and sorting.
Practice Print DFS
Write dfs_print(graph, start). Run stack-based DFS and print the visit order with print(). Output: [0, 2, 3, 1].
Starter code
def dfs_print(graph, start):
# Print DFS orderSample solution
def dfs_print(graph, start):
# Print DFS order
visited = []
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
for nb in reversed(graph[node]):
if nb not in visited:
stack.append(nb)
print(visited)
dfs_print({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0)Expected output
[0, 2, 3, 1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Summary - DFS: match the terms
| Term | Meaning |
|---|---|
DFS |
Stack |
recursion |
Self-call |
backtrack |
Return |
visited |
No repeat |
2 Stack op
node = stack.____
node = stack.pop()
Explanation: pop() is right.
3 What is DFS's time complexity?
- O(V log V)
- O(V + E) Correct answer
- O(E^2)
- O(V!)
Explanation: O(V + E).