Graphs · Exercise 38 of 100

Adjacency lists and matrices

An adjacency list stores each vertex's neighbors, so you can visit them without checking every vertex. An adjacency matrix uses one row and one column per vertex, with a 1 where an edge exists and a 0 elsewhere. For an undirected edge between two different vertices, record each endpoint as a neighbor of the other.

Try it yourself

Four towns have exactly four two-way roads, AB, AC, BC and CD. How many cells contain a 1 in the adjacency matrix?

One-step hint

Label both axes with the towns. For road AB, mark row A, column B and its mirror across the diagonal. Treat each remaining road the same way.

Worked solution
  1. A lists B and C as neighbors, B lists A and C, C lists A, B and D, and D lists C.
  2. Each listed neighbor contributes one 1 to its town's row, giving 2 + 2 + 3 + 1 = 8 cells.
DSA compiler