Skip to main content

Depth-First Search (DFS)

Definition​

Depth-First Search (DFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph. It starts at a chosen node and explores as far as possible along each branch before backtracking

Practice​

DFS(graph, start_node):
initialize an empty stack
push start_node onto the stack
initialize an empty set to keep track of visited nodes

while stack is not empty:
current_node = pop from stack
if current_node is not visited:
mark current_node as visited
visit current_node

for each neighbor in graph[current_node]:
if neighbor is not visited:
push neighbor onto stack