DFS of Graph
DFS of Graph is a GFG problem (Easy). You get a connected undirected graph as an adjacency list adj: adj[i] holds the neighbours of vertex i. Return the vertices in depth-first order, starting from vertex 0.
- Look at the neighbours of each vertex in the order
adj[i]gives them. The judge compares your list with one exact sequence. - The graph may contain cycles, but every vertex must appear exactly once.
With up to 10⁴ vertices and edges, the traversal must touch each vertex and edge only a constant number of times.
- 1 <= V = adj.size() <= 10⁴
- 0 <= adj[i][j] < V
- The graph is connected and undirected
Intuition
Depth-first search behaves like walking a maze with one hand on the wall: keep stepping to a new vertex until you are stuck, then back up to the last vertex that still has an unexplored neighbour.
- Go deep: move into the first neighbour that has not been visited yet.
- Back up: when no neighbour is new, return to the vertex you came from and continue its list where you stopped. Recursion does this for free: each call waits on the call stack until its child returns.
- Mark on arrival: a cycle leads back to vertices already seen. Marking a vertex the moment you enter it means no edge can bring you into it a second time.
Use DFS when a problem needs every vertex reachable from a start, or needs to follow one path to its end before trying another: counting islands, finding connected components, detecting cycles, topological sorting. Most of those are this same walk with one extra line added at arrival or at return.
Approach
Before reading on, run the first example by hand: adj = [[2, 3, 1], [0], [0, 4], [0], [2]]. Keep a list of the vertices you are "inside". When you reach vertex 4, which vertex do you return to, and which neighbour of 0 is looked at next?
Mark and record vertex 0
Create visited with every entry False, then call visit(0). The call sets visited[0] and appends 0 to order before it reads a single neighbour, so no edge back to 0 can add it again.
Check neighbours in list order
Loop over adj[u] from left to right, the order the expected answer uses. Skip a neighbour that is already visited: it is either finished or still waiting on the call stack, and entering it again would list it twice.
Go into the first new neighbour at once
As soon as an unvisited neighbour v turns up, call visit(v). The loop over adj[u] pauses mid-way and waits on the call stack, which is what makes recursive DFS depth-first: v and everything new beyond it come before u's remaining neighbours.
Return when the list runs out
When visit(u) has checked every neighbour, it returns. Control goes back to the caller's loop, right after the neighbour that led to u. This return is the backtrack; no extra bookkeeping is needed.
Why each vertex appears exactly once
A vertex is appended only at the moment it is marked, and a marked vertex is never entered again, so nothing repeats. Because the graph is connected, every vertex has a path from 0, and the walk does not stop until every vertex on such a path is marked.
Code in Python, C++ and Java
Common pitfalls
Marking the vertex after its neighbours
def visit(u):
for v in adj[u]:
if not visited[v]:
visit(v)
visited[u] = True
order.append(u)def visit(u):
visited[u] = True
order.append(u)
for v in adj[u]:
if not visited[v]:
visit(v)On adj = [[1], [0]], visit(0) enters 1, and 1 sees 0 still unmarked and enters it again. The two calls feed each other until the stack overflows. The mark has to be set on arrival.
Sorting the neighbours first
for v in sorted(adj[u]):
for v in adj[u]:
For adj = [[2, 3, 1], [0], [0, 4], [0], [2]] the expected answer is [0, 2, 4, 3, 1]. Sorting makes 0 try 1 first and returns [0, 1, 2, 4, 3], which is a valid DFS but not the one the judge checks.
Ignoring recursion depth on a long chain
class Solution:
def dfs(self, adj):
visited = [False] * len(adj)class Solution:
def dfs(self, adj):
sys.setrecursionlimit(20000)
visited = [False] * len(adj)A chain 0 - 1 - 2 - ... - 9999 makes every call wait on the next, 10⁴ deep. Python stops at about 1,000 nested calls and raises RecursionError. Java's default thread stack can also run out near this depth; the explicit-stack version in the FAQ below has no depth limit.
Edge cases
adj = [[]]visit(0) marks and records 0, finds an empty list and returns. The answer is [0].
Complexity
visited, order and the call stack each hold at most V entries.DFS of Graph FAQ
Can DFS use a stack instead of recursion?
Push 0. Then repeat: pop a vertex; if it is already visited, skip it; otherwise mark it, record it, and push its neighbours in reverse so the first neighbour is popped first.
Mark when a vertex is popped, not when it is pushed. On adj = [[1, 3], [0, 2], [1, 3, 4], [0, 2], [2]] recursion gives [0, 1, 2, 3, 4], but marking on push lets 0 claim vertex 3 early, so 2 skips it and the stack version returns [0, 1, 2, 4, 3].
What changes if the graph is disconnected?
A single visit(0) only reaches the part of the graph that contains 0. Loop s over all vertices and call visit(s) whenever s is still unvisited; each call covers one component. The total work is still O(V + E).
Can a graph have more than one correct DFS order?
Yes. Any order that always moves to some unvisited neighbour before backing up is a depth-first order, so changing the neighbour order changes the answer. This problem fixes the choice to the order in adj[i], which leaves exactly one correct output.