Depth-First Search visualization

Go as deep as possible along each branch before backtracking.

DFS dives into the first unvisited neighbour, then its first unvisited neighbour, and so on. When stuck, it backtracks — the call stack remembers where to return.

Discovery and finish times power cycle detection, topological sorting and strongly connected components.

Complexity

Time: best O(V + E), average O(V + E), worst O(V + E). Space: O(V). Difficulty: Beginner.

Pseudocode

procedure DFS(G, u):
  visited.add(u); record discovery of u
  for each neighbor v of u:
    if v not visited:
      DFS(G, v)
  u is finished (backtrack)

More graphs algorithms