Graph algorithms operate on adjacency list or matrix representations. BFS explores layer-by-layer, giving shortest path on unweighted graphs. DFS explores deeply first, enabling cycle detection, topological sort, and connected components. Kahn's algorithm produces topological order and detects cycles via in-degree processing. Three-colour DFS (white/gray/black) detects back-edges (cycles). Union-Find tracks connected components in near-O(1).
Each stage in order — click any step to read what it does.
Queue-based BFS and Stack-based DFS traversal comparison.
The trade-offs worth knowing before you build this.
BFS gives shortest path (unweighted). DFS reveals structure: topological order, cycles, SCCs. Know which you need before coding.
If Kahn's topological sort processes fewer than V nodes, the graph has a cycle. No separate cycle-detection pass needed.
For "are nodes X and Y connected?" with incremental edge additions, Union-Find is near-O(1) per operation — far faster than rerunning BFS.
Sign in to share your feedback and join the discussion.