Loading...
Depth-First Search performs a systematic exploration of a graph by diving deep along each branch before backtracking. It exposes structural properties like discovery/finish times, back edges (cycles), and enables multiple fundamental algorithms.
Given a graph G = (V, E), DFS explores edges out of the most recently discovered vertex that still has unexplored neighbors. It produces a depth-first forest of rooted trees capturing parent relationships of the traversal.
Each vertex discovered and finished once; each edge examined at most twice (undirected) or once (directed).
1DFS(G):2 for each vertex v in G:3 color[v] ← WHITE4 parent[v] ← NIL5 time ← 06 for each vertex v in G:7 if color[v] = WHITE:8 DFS-Visit(G, v)9 10DFS-Visit(G, u):11 color[u] ← GRAY12 time ← time + 113 discover[u] ← time14 for each neighbor v of u:15 if color[v] = WHITE:16 parent[v] ← u17 DFS-Visit(G, v)18 color[u] ← BLACK19 time ← time + 120 finish[u] ← time