Bitpath

Graphs

Friends, roads, courses, grids: most real problems are graphs in disguise. Learn to store them, walk them breadth-first and depth-first, order them, find their cycles and compute cheapest routes and networks.

  • Intermediate
  • 4 units, 12 lessons, 134 exercises
  • Python, JavaScript or TypeScript
  • Builds on Recursion & Backtracking, Data Structures, heaps from Trees & Heaps

Unit 01 · 3 lessons

Modeling graphs

Turn a problem into nodes and edges, and store them the right way

  1. > start01Nodes and edges
  2. 02List or matrix
  3. BOSSGrids are graphs
Unit prize
  1. 01
    Nodes and edges

    Directed, undirected, and the adjacency list

  2. 02
    List or matrix

    Two ways to store a graph, and what each costs

  3. BOSS
    Grids are graphs

    Find the neighbours of a cell without leaving the grid

Read the unit guide

A graph is a set of nodes (things) and edges (connections between two things). People and friendships, cities and roads, courses and prerequisites, cells of a grid and the moves between them: once you see the nodes and edges, the same few algorithms solve all of them.

Edges are either undirected (a friendship goes both ways) or directed (a follow goes one way). The number of edges touching a node is its degree. In a directed graph, edges leaving a node are its out-degree and edges arriving are its in-degree.

The standard storage is an adjacency list: for every node, the list of its neighbours. An undirected edge appears twice, once in each end's list. Memory is O(V + E), and you can loop over a node's neighbours without touching anything else. Give every node a list, even an empty one.

An adjacency matrix is a V × V grid where m[a][b] says whether the edge exists (or holds its weight). Checking one edge is O(1), but memory is O(V²) no matter how few edges there are, and listing a node's neighbours scans a whole row. Use it for small, dense graphs.

A grid is a graph nobody wrote down. Each cell is a node, and its neighbours are found by adding direction deltas such as (-1, 0) and (0, 1) to its row and column. Always check bounds before reading a neighbour: an off-grid index is a bug that does not always crash.

Unit 02 · 3 lessons

BFS and DFS

Visit every reachable node exactly once, in the order the problem needs

  1. 01Breadth-first search
  2. 02Depth-first search
  3. BOSSCount the islands
Unit prize
  1. 01
    Breadth-first search

    Explore in rings and get the fewest hops for free

  2. 02
    Depth-first search

    Go deep, back up at dead ends

  3. BOSS
    Count the islands

    One flood fill per connected component

Read the unit guide

Almost every graph algorithm is a traversal with a twist. A traversal starts at one node and follows edges until it has seen everything reachable. The one rule: remember which nodes you have already seen, or a cycle will keep you walking forever.

Breadth-first search (BFS) explores in rings: the start, then its neighbours, then their neighbours. It keeps a queue of nodes that are discovered but not yet explored. Because nodes come out in order of distance, the first time BFS reaches a node is along a path with the fewest edges. Storing dist[nxt] = dist[node] + 1 turns it into a shortest-path algorithm for unweighted graphs.

Mark a node as seen at the moment you put it in the queue, not when you take it out. Otherwise two neighbours can both add it and the work is duplicated.

Depth-first search (DFS) goes as deep as it can and backs up only at dead ends. Written recursively, the call stack remembers the way back; written with a loop, an explicit stack does. DFS answers "what can I reach?" in very little code, but the path it finds is not the shortest, and deep recursion can overflow the call stack on long chains.

Both visit each node once and look at each edge once: O(V + E) with an adjacency list. To cover a graph that is in several pieces, start a new traversal from every node not yet seen. Each start discovers one connected component, which is how you count islands, friend groups or networks.

Unit 03 · 3 lessons

Order and cycles

Put dependent tasks in a valid order, detect cycles and track groups as they merge

  1. 01Topological sort
  2. 02Finding cycles
  3. BOSSUnion-find
Unit prize
  1. 01
    Topological sort

    Order tasks so every prerequisite comes first

  2. 02
    Finding cycles

    Three states for directed graphs, a parent check for undirected

  3. BOSS
    Union-find

    Track groups as they merge, in almost constant time

Read the unit guide

Some arrows mean "must come before": a course and its prerequisites, the steps of a build, socks and shoes. A topological order lines the nodes up so that every arrow points forward. There are usually several valid orders, and any one of them will do.

Kahn's algorithm builds one. Count, for every node, how many arrows point into it: its in-degree. A node with in-degree 0 waits for nothing, so it can go next. Output it, lower the in-degree of everything it points to, and any node that drops to 0 becomes ready. Every node and every edge is handled once: O(V + E).

An order exists only if the graph has no cycle. If A waits for B and B waits for A, neither can ever go first. Kahn's algorithm detects this for free: the nodes on a cycle never reach in-degree 0, so the output comes up short.

A depth-first search finds cycles with three states: not visited, on the current path, finished. An edge into a node on the current path leads back to where you already are: a cycle. An edge into a finished node is harmless, it is only a second route to the same place.

Undirected graphs are simpler. Each edge is stored in both directions, so ignore the node you just came from; any other visited neighbour closes a loop.

Union-find answers "are these two connected?" while edges keep arriving. Every item points at a parent, and the root of each group is its own parent. find follows parents to the root and flattens the path behind it; union links one root under the other. Both run in almost constant time.

Unit 04 · 3 lessons

Weighted paths

Find cheapest routes and cheapest networks when every edge has a cost

  1. 01Dijkstra's algorithm
  2. 02When Dijkstra breaks
  3. BOSSMinimum spanning tree
Unit prize
  1. 01
    Dijkstra's algorithm

    Closest node first, with a heap

  2. 02
    When Dijkstra breaks

    Negative edges and Bellman-Ford

  3. BOSS
    Minimum spanning tree

    Connect everything for the least total cost

Read the unit guide

Put a number on every edge, a distance, a price or a time, and "shortest" changes meaning. The route with the fewest edges may no longer be the cheapest, so breadth-first search stops giving the right answer.

All shortest-path algorithms share one move, called relaxing an edge. Keep the best distance found so far for every node: 0 for the start, infinity for the rest. For an edge from u to v with weight w, ask whether dist[u] + w beats dist[v], and lower it if so. The algorithms differ only in the order in which they relax.

Dijkstra's algorithm always continues from the closest node that is not finished yet, taken from a min-heap of (distance, node) pairs. Since weights are never negative, nothing found later can improve that node, so its distance is final. Improvements are pushed as new pairs, and an outdated pair is skipped when it surfaces. The cost is O((V + E) log V).

One negative edge breaks that reasoning: a longer route can now be cheaper. Bellman-Ford handles it with patience instead of cleverness. It relaxes every edge, V − 1 times over, for O(V × E). If an edge can still be relaxed after that, the graph has a cycle with a negative total, and no shortest path exists.

A different question: which edges connect everything for the least total weight? The answer is a minimum spanning tree, with exactly V − 1 edges. Kruskal's algorithm takes edges from cheapest to dearest and uses union-find to skip any edge that would close a cycle. Prim's algorithm grows a single tree outwards, always adding the cheapest edge that leaves it.

Choose by the graph you have: no weights, breadth-first search; weights of zero or more, Dijkstra; negative weights, Bellman-Ford; cheapest network rather than cheapest route, a minimum spanning tree.

Learn Graphs on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy