GeeksforGeeks Easy

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.

Constraints
  • 1 <= V = adj.size() <= 10⁴
  • 0 <= adj[i][j] < V
  • The graph is connected and undirected
graphdfstraversal
Open on GeeksforGeeks ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1import sys
▶2 
▶3class Solution:
▶4 def dfs(self, adj):
▶5 sys.setrecursionlimit(20000)
▶6 visited = [False] * len(adj)
▶7 order = []
▶8 
▶9 def visit(u):
▶10 visited[u] = True
▶11 order.append(u)
▶12 for v in adj[u]:
▶13 if not visited[v]:
▶14 visit(v)
▶15 
▶16 visit(0)
▶17 return order
walked downchecking01234call stackat 0order0start at 0 → mark it, write it down
u0
order[0]
The traversal begins at vertex 0. It is marked visited before any neighbour is looked at, so no edge can lead back into it and add it a second time.
walked downchecking01234call stackat 0at 2order022 is new → go deeper into 2
u2came from 0
order[0, 2]
depth2
Vertex 2 has not been visited, so DFS leaves 0 half-finished and moves into 2 right away. A new frame goes on the call stack, 2 is marked and it takes slot 1 in the order. Vertex 0 will continue with its next neighbour only after everything reachable through 2 is done.
walked downchecking01234call stackat 0at 2order020 already visited → skip
u2
neighbour0visited
Next in the list of 2 is 0. 0 is the vertex we just came from. Its mark is already set, so DFS does not enter it again. Without that check the walk would bounce along this edge forever.
walked downchecking01234call stackat 0at 2at 4order0244 is new → go deeper into 4
u4came from 2
order[0, 2, 4]
depth3
Vertex 4 has not been visited, so DFS leaves 2 half-finished and moves into 4 right away. A new frame goes on the call stack, 4 is marked and it takes slot 2 in the order. Vertex 2 will continue with its next neighbour only after everything reachable through 4 is done.
walked downchecking01234call stackat 0at 2at 4order0242 already visited → skip
u4
neighbour2visited
Next in the list of 4 is 2. 2 is the vertex we just came from. Its mark is already set, so DFS does not enter it again. Without that check the walk would bounce along this edge forever.
walked downchecking01234call stackat 0at 2order0244 has no neighbours left → back to 2
finished4
stack[0, 2]
Every neighbour of 4 has been handled, so its call returns. That is the backtrack: DFS is back at 2 and picks up its list where it stopped.
walked downchecking01234call stackat 0order0242 has no neighbours left → back to 0
finished2
stack[0]
Every neighbour of 2 has been handled, so its call returns. That is the backtrack: DFS is back at 0 and picks up its list where it stopped.
walked downchecking01234call stackat 0at 3order02433 is new → go deeper into 3
u3came from 0
order[0, 2, 4, 3]
depth2
Vertex 3 has not been visited, so DFS leaves 0 half-finished and moves into 3 right away. A new frame goes on the call stack, 3 is marked and it takes slot 3 in the order. Vertex 0 will continue with its next neighbour only after everything reachable through 3 is done.
walked downchecking01234call stackat 0at 3order02430 already visited → skip
u3
neighbour0visited
Next in the list of 3 is 0. 0 is the vertex we just came from. Its mark is already set, so DFS does not enter it again. Without that check the walk would bounce along this edge forever.
walked downchecking01234call stackat 0order02433 has no neighbours left → back to 0
finished3
stack[0]
Every neighbour of 3 has been handled, so its call returns. That is the backtrack: DFS is back at 0 and picks up its list where it stopped.
walked downchecking01234call stackat 0at 1order024311 is new → go deeper into 1
u1came from 0
order[0, 2, 4, 3, 1]
depth2
Vertex 1 has not been visited, so DFS leaves 0 half-finished and moves into 1 right away. A new frame goes on the call stack, 1 is marked and it takes slot 4 in the order. Vertex 0 will continue with its next neighbour only after everything reachable through 1 is done.
walked downchecking01234call stackat 0at 1order024310 already visited → skip
u1
neighbour0visited
Next in the list of 1 is 0. 0 is the vertex we just came from. Its mark is already set, so DFS does not enter it again. Without that check the walk would bounce along this edge forever.
walked downchecking01234call stackat 0order024311 has no neighbours left → back to 0
finished1
stack[0]
Every neighbour of 1 has been handled, so its call returns. That is the backtrack: DFS is back at 0 and picks up its list where it stopped.
walked downchecking01234call stackemptyorder024310 has no neighbours left → stack empty
finished0
stackempty
Every neighbour of 0 has been handled, so its frame is removed and the call stack is empty. Nothing is left half-finished.
walked downchecking01234call stackemptyorder02431all 5 vertices visited → return the order
result[0, 2, 4, 3, 1]
The answer is [0, 2, 4, 3, 1]. The green edges are the ones DFS walked down; together they form a tree that reaches every vertex once. The grey edges were only checked and skipped.
05

Common pitfalls

Marking the vertex after its neighbours

✗ Wrong
def visit(u):
    for v in adj[u]:
        if not visited[v]:
            visit(v)
    visited[u] = True
    order.append(u)
✓ Right
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

✗ Wrong
for v in sorted(adj[u]):
✓ Right
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

✗ Wrong
class Solution:
    def dfs(self, adj):
        visited = [False] * len(adj)
✓ Right
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.

06

Edge cases

Only one vertex, adj = [[]]

visit(0) marks and records 0, finds an empty list and returns. The answer is [0].

07

Complexity

Time
O(V + E)
Space
O(V)
Each vertex is entered once, and each undirected edge is looked at once from each end. visited, order and the call stack each hold at most V entries.
08

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.