Graph Representation
A graph is a map. Imagine a country with cities (vertices, V) connected by roads (edges, E). A graph lets you model any network — flight routes, social connections, web links.
Two ways to store the map
You've built a map of 5 cities. Now where do you write down which roads connect which cities? You have two classic choices:
Adjacency List
Keep a contact list for each city. City A's list says: "I connect to B and C." City B's list says: "I connect to A and D." This is memory-efficient — you only store roads that actually exist. If most cities aren't directly connected, you save a ton of space.
Adjacency Matrix
Draw a grid with every city on both axes. Put a 1 in the cell where city X and city Y share a road. Every pair of cities gets a cell — even ones with no road between them. Fast to check "is there a road from X to Y?" — but uses \(V^2\) space even if the map is mostly empty.
Directed vs Undirected
An undirected graph has two-way roads — if you can drive from A to B, you can drive back. A directed graph (digraph) has one-way streets — a road from A to B doesn't mean there's a road from B to A. Think of Twitter follows vs Facebook friends.
Weighted Graphs
Roads have distances. A weighted graph stores a number on each edge — the cost, distance, or travel time. Weighted graphs are central to shortest-path algorithms like Dijkstra's and Bellman-Ford. In an adjacency list you store pairs: (neighbor, weight). In a matrix you store the weight instead of 1.
← → arrow keys to step · click elements to interact