Algo-Sim › Graph Traversal
Depth-First Search
Easy · Graph Traversal · step through it in Java, Python and C++ on your own input
Visit every node reachable from start by going as deep as possible before backtracking. The call stack is the path from start to the current node.
Problem
An undirected graph has nodes 0..n − 1 and the given edges. Starting from start, list every reachable node in depth-first order: follow one unvisited neighbour as deep as possible before backing up. Neighbours are taken in increasing order.
Constraints
- 1 ≤ n ≤ 10⁵ and 0 ≤ edges ≤ 2 · 10⁵ in typical problems
- O(V + E) time
- Recursion depth can reach V: deep graphs may need an explicit stack
Edge cases to test
- A cycle (needs a visited set)
- A disconnected graph
- A very deep path (stack overflow with recursion)
Follow-up questions
- How do you avoid stack overflow?
- Use an explicit stack, or raise the limit (Python’s recursion limit is about 1,000 by default).
- What can DFS find that BFS can’t easily?
- Cycles via back edges, topological order from finish times, bridges and articulation points from discovery and low times.
Solution
Java
public List<Integer> dfs(List<List<Integer>> adj, int start) {
List<Integer> order = new ArrayList<>();
dfs(adj, start, new boolean[adj.size()], order);
return order;
}
private void dfs(List<List<Integer>> adj, int node, boolean[] visited, List<Integer> order) {
visited[node] = true;
order.add(node);
for (int next : adj.get(node)) {
if (!visited[next]) {
dfs(adj, next, visited, order);
}
}
}Python
def dfs(adj, start):
order = []
visited = [False] * len(adj)
def visit(node):
visited[node] = True
order.append(node)
for neighbor in adj[node]:
if not visited[neighbor]:
visit(neighbor)
visit(start)
return orderC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> dfs(vector<vector<int>> &adj, int start) {
vector<int> order = {};
vector<bool> visited(adj.size());
dfs(adj, start, visited, order);
return order;
}
void dfs(vector<vector<int>> &adj, int node, vector<bool> &visited, vector<int> &order) {
visited[node] = true;
order.push_back(node);
for (int next : adj[node]) {
if (!visited[next]) {
dfs(adj, next, visited, order);
}
}
}
};
More Graph Traversal problems
- Breadth-First Search (Easy)
- Course Schedule (cycle detection) (Medium)
- Graph Valid Tree (undirected cycle) (Medium)
- Number of Connected Components (DFS) (Medium)
- Is Graph Bipartite? (Medium)
- Clone Graph (Medium)
- Word Ladder (Hard)
- Open the Lock (Medium)