Graph Traversals
Explore how to systematically visit all nodes in a graph using breadth-first search and depth-first search. Learn JavaScript implementations, analyze time and space complexities, and discover when to apply each traversal method in graph-related problems.
Graph traversal is the process of visiting all vertices (nodes) in a graph systematically. It is a fundamental concept because many graph algorithms rely on efficient graph exploration.
The two most common graph traversal techniques are:
Breadth-first search (BFS)
Depth-first search (DFS)
Breadth-first search (BFS)
Breadth-First Search explores a graph level by level. Starting from a chosen node, it first visits all immediate neighbors before moving to nodes at the next level.
Key idea
BFS uses a queue (FIFO: first in, first out).
How BFS works
Start from a chosen node.
Mark it as visited.
Add it to a queue.
While the queue is not empty:
Dequeue a node.
Visit all its unvisited neighbors.
Mark them as visited and add them to the queue.
Below is the JavaScript implementation of BFS:
Time complexity:
The time complexity of BFS is