Graphs

How to store a graph, and how BFS and DFS walk it: shortest paths without weights, connected pieces, cycles and dependency order.

Overview

A graph is a set of nodes (also called vertices) joined by edges. It models anything where things connect: people and friendships, cities and roads, tasks and the tasks they wait on. A grid is a graph too, where each cell connects to the cells next to it.

Most graph questions reduce to one of two walks. Breadth-first search (BFS) spreads out one step at a time. Depth-first search (DFS) follows one path as far as it goes, then backs up. Both touch every node and edge once, so both take O(V + E) time, where V is the number of nodes and E the number of edges. This chapter runs both walks on one small graph, then uses them to find cycles, to pick the right algorithm for a question, and to walk a grid.

Each section below follows the same shape: the rule first, then the rule on a small graph, then the trap to avoid.

The words you need

The rule: ask three things about any graph question: is it directed, is it weighted, and can it have cycles? Those three answers pick the algorithm.

  • Directed: an edge goes one way only, from u to v, like a follow or a prerequisite.
  • Undirected: an edge works both ways, like a friendship or a two-way road.
  • Weighted: each edge has a cost, such as a distance, a time or a price.
  • Degree: the number of edges touching a node. Directed graphs split it in two: the in-degree counts the edges coming in, and the out-degree counts the edges going out.
  • Cycle: a path that returns to where it started.
  • DAG: a directed acyclic graph, a directed graph with no cycle. Only a DAG has a dependency order.
  • Connected component: a largest group of nodes that can all reach each other.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio