Back to stories
<Engineering/>
Premium

Graph Algorithms: BFS and DFS in Practice

Share by

Graph Algorithms: BFS and DFS in Practice

Breadth-first search (BFS) and depth-first search (DFS) are two fundamental ways to traverse a graph. They differ in the order nodes are visited and lead to different algorithms for shortest path, connectivity, and more. This post explains both and when to use each.


Graph basics

A graph has vertices (nodes) and edges (connections). It can be directed (one-way edges) or undirected (two-way). Represented in code as adjacency list (each node → list of neighbors) or adjacency matrix; list is usually better for sparse graphs.