Command Palette

Search for a command to run...

Module 20

Graph Fundamentals

Nodes and edges: directed, undirected and weighted graphs, adjacency lists and matrices, degrees, and grids treated as graphs.

Intermediate 4 lessons 6 problems ~45 min of lessons

A graph is the most general structure in this course: things (nodes) and connections between them (edges). Road maps, social networks, course prerequisites, web links and game boards are all graphs. Trees and linked lists are special graphs with extra rules.

This module gives you the vocabulary and the three ways to store a graph in code, shows how to read problems as graphs (including 2D grids, where every cell is a node), and solves first problems that need nothing more than degrees and a single traversal. The next modules build BFS, DFS, topological sort, union-find, shortest paths and spanning trees on top of it.

Best after: Binary Trees

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Reading structure from edges: the centre is the node shared by every edge, so two edges are enough.

  2. In-degree and out-degree on a directed graph, computed straight from the edge list.

  3. The first traversal: build an adjacency list, then explore from the source with a visited array.

  4. In-degree reasoning on a DAG: a node with no incoming edge can only be reached by starting there.

  5. Degrees plus an adjacency matrix for O(1) "are these two connected?" checks.

  6. Grid as graph without a traversal: count land cells and shared sides.