Implement DFS Algo
Pattern: BFS and DFS
Depth-first search from vertex 0: mark the vertex, record it, then for each neighbour in order, if it is unmarked, search from it before trying the next neighbour.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given an adjacency list, return the recursive DFS order starting from vertex 0, trying neighbours in the order listed.
Think first
- After visiting a vertex, which one comes next?
- When do you come back to try the next neighbour?
- What stops infinite loops?
Hints
Brute force, and why it fails
The iterative version with an explicit stack gives the same order if neighbours are pushed in reverse.
The key insight
Recursion goes as deep as possible along each neighbour before trying the next, which defines DFS order.
Dry run
| out | 0 |
|---|
adj = [[2, 3, 1], [0], [0, 4], [0], [2]]. Visit 0; its first neighbour is 2.
Step 1 of 3
The plan
dfs(u): mark u; out += u
for v in adj[u]: if v unmarked: dfs(v)
Complexity
- Time
O(V + E)- Space
O(V)
Each vertex once; the recursion can be V deep.
Edge cases
- A single vertex with no edges.
- A graph in several pieces.
- Many edges at one vertex.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> dfsOfGraph(int[][] adj) {
List<Integer> out = new ArrayList<>();
dfs(0, adj, new boolean[adj.length], out);
return out;
}
private void dfs(int u, int[][] adj, boolean[] seen, List<Integer> out) {
seen[u] = true;
out.add(u);
for (int v : adj[u]) if (!seen[v]) dfs(v, adj, seen, out); // go deeper before trying the next neighbour
}
}C++
class Solution {
public:
vector<int> dfsOfGraph(vector<vector<int>>& adj) {
vector<int> out;
vector<bool> seen(adj.size(), false);
dfs(0, adj, seen, out);
return out;
}
void dfs(int u, vector<vector<int>>& adj, vector<bool>& seen, vector<int>& out) {
seen[u] = true;
out.push_back(u);
for (int v : adj[u]) if (!seen[v]) dfs(v, adj, seen, out); // go deeper before trying the next neighbour
}
};Python
class Solution:
def dfsOfGraph(self, adj: list[list[int]]) -> list[int]:
out, seen = [], set()
def dfs(u):
seen.add(u)
out.append(u)
for v in adj[u]:
if v not in seen:
dfs(v) # go deeper before trying the next neighbour
dfs(0)
return outCommon mistakes
- Pushing neighbours onto a stack in the given order, which reverses them.
- Forgetting the visited marks on cyclic graphs.