Skip to content
Data Structures & Algorithmsintermediate · 60 min

Graphs (BFS, DFS)

Nodes connected by edges — the most general structure. Know adjacency representations, BFS vs DFS, and the classic algorithms: topological sort, shortest paths, and cycle detection.

Representation

An adjacency list (map of node → neighbours) uses O(V + E) space and is best for sparse graphs; an adjacency matrix uses O(V²) but gives O(1) edge lookups. Graphs may be directed or undirected, weighted or unweighted, cyclic or acyclic.

BFS vs DFS

BFS (queue) explores level by level and finds the shortest path in an unweighted graph. DFS (stack/recursion) dives deep first and underlies cycle detection, topological sort, and connected-components. Both are O(V + E); always track a visited set to avoid infinite loops.

Weighted shortest paths

Dijkstra's algorithm (a priority queue / min-heap) finds shortest paths with non-negative weights in O((V + E) log V). For graphs with negative edges use Bellman-Ford; for all-pairs use Floyd-Warshall.

Resources

Practice & test yourself

Take the quiz →