Adjacency List

Learn how to represent a graph using the adjacency lists representation.

What a waste!

An n×nn\times n matrix requires n2n^2 memory. Imagine a graph on a thousand vertices, with a handful of edges incident on each vertex. In the adjacency matrix, the row for each vertex would contain mostly zeroes except for a smattering of ones.

That’s wasteful as far as memory is concerned because if we know the neighbors of a vertex, it is easy to infer which of the vertices are not its neighbors. We don’t really need to store a zero against each nonneighbor.

For instance, the adjacency matrix for the shown graph has 6464 entries in all, but only 1414 are non-zero.

Get hands-on with 1400+ tech skills courses.