- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Graph Traversal: BFS and DFS
Graphs
Graph Traversal: BFS and DFS
BFS and DFS differ by one thing: a queue or a stack. Everything else is identical, including the visited set you cannot leave out.
Why visited is not optional
A tree has no cycles, so you can walk it without tracking where you have been. A graph can loop back, and without a visited set the traversal runs forever.
Breadth first - a queue
Visit all neighbours, then their neighbours. Reaches nodes in order of distance, which is why it finds shortest paths in unweighted graphs.
BFS, with distances
javascript
