Graph Traversals
Explore graph traversal methods such as breadth-first search (BFS) and depth-first search (DFS) using JavaScript. Learn how BFS explores nodes level by level while DFS explores deeply along paths. Understand their implementations, time and space complexities, and practical applications like shortest path and cycle detection.
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