Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Concept

Graphs Overview

Nodes, edges, and why DFS needs a visited set
step 1 / 32
undirected graph (has a cycle)
0
1
2
3
4
call stack
(empty)
DFS with a visited set
1dfs(graph):
2 visited = {}
3 dfs(u):
4 if u in visited: return // never re-enter
5 mark u visited
6 for v in adj[u]: dfs(v)
7 return
state
  • nodes (V)5
  • edges (E)5
  • cycle0-1-2-0

line 1A graph is just nodes plus edges. Unlike a tree it has no root, and edges can form cycles — here 0–1–2–0 is a loop. There is no parent/child direction to stop us, so a naive DFS would walk 0→1→2→0→1→2… forever. The fix is a visited set: mark a node before recursing, and never re-enter a marked node.