Algorithms Made Simple

Graphs and How to Store Them: Matrix or List?

Nodes, edges and weights, and why most real networks are best stored as adjacency lists.

Algorithms Made Simple · 4 min read

Roads, friendships, web links and flight routes are all graphs. Choosing how to store one in memory changes how fast everything else runs.

The pieces

A graph is a set of nodes joined by edges. Edges can be undirected, as in a friendship that goes both ways, or directed, as in a link from one page to another. Edges can also carry weights, such as distance or cost.

Adjacency matrix

Make a square grid with one row and one column per node. Put a mark in cell (a, b) when an edge joins a to b. Checking whether two nodes are connected takes one step. But the grid has n × n cells, so 10,000 nodes need 100 million cells, even if most are empty.

Adjacency list

Give each node a list of its neighbors. The memory used is proportional to the number of nodes plus the number of edges. Finding a node’s neighbors is quick. Checking one specific pair means scanning a short list.

Which to choose

  • Sparse graphs, where each node touches only a few others (roads, social networks): adjacency lists.
  • Dense graphs, or when you must test edges constantly: an adjacency matrix can be a good fit.
  • Most real networks are sparse, so lists are the usual default.

Start by asking the right question

Before coding, decide what the nodes and edges are, whether edges have direction or weight, and which question you need to answer. The representation should make that question cheap.

More guides from this book