teach-ict.com logo

THE education site for computer science and ICT

2. Storing graphs - Adjacency Matrix

Humans can intuitively grasp the structure of a graph by looking at a diagram. But computers need things to be spelled out more explicitly.

There are two popular ways of storing graph data in a computer-friendly format:

  • Adjacency matrices
  • Adjacency lists

Let's use the following graph as an example:

The first step to creating an adjacency matrix is to make a table. The table should have a column for every vertex in the graph, and a row for every vertex too.

This graph has vertices A, B, C, D, E, and F. So the table would start out looking like this:

Going across each row, put a 1 in the columns for the nodes that vertex connects to.

A connects with C and nothing else, so the first row looks like this:

Continue going down the rows and filling in. You'll end up with a matrix that looks like this:

This matrix lists every connection in the graph as a 1. The rest of the entries should be filled with zeroes, showing that there is no connection between those two vertices:

This is a completed adjacency matrix.

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Graphs adjacency matrix