8.1Graph with an Adjacency Matrix
A graph in a matrix: creating it
The most direct way to keep a graph in memory is a table. The vertices are numbered from 0 to n-1 and an n × n matrix is set up: the cell where row u meets column v tells whether there is an edge from u to v. This table is called an adjacency matrix. In this lesson you build the empty graph, that is, a matrix whose cells are all 0.
- What a cell of an adjacency matrix shows
- The fields of
struct Graph:n,directedandadj - Why the empty graph is a matrix with every cell 0
1Idea
If cell adj[u][v] is 1, there is an edge from vertex u to vertex v; if it is 0, there is none. In an undirected graph an edge has no direction, so one edge is written into two cells: adj[u][v] and adj[v][u]. That is why the matrix of an undirected graph is symmetric about its diagonal. In a directed graph only adj[u][v] is written.
struct Graph keeps three things: the number of vertices n, whether the graph is directed, directed, and the matrix itself, adj. In C the size of the matrix must be known when compiling, so room is set aside for at most MAX vertices and only the top-left n × n part is used. In Java and Python the matrix is made exactly n × n.
create sets the used part of the matrix to 0 row by row. In C a local array may hold random leftover values, so clearing it is a must. Java starts every cell of a new array at 0 on its own. In Python every row is built as its own list. You will add the edges one by one in the next lesson.
The number of 1s in a row is the degree of that vertex. In the example row 1 has three 1s: vertex 1 is joined to 0, 2 and 4.
2Step by step
The drawing shows the graph on the left and the adj matrix on the right; row numbers are on the left, column numbers on top. create(&g, 6, false) clears the matrix row by row.
create(&g, 6, false)is called.nbecomes 6 anddirectedfalse. In C the cells of the matrix hold random leftover values (?).i = 0: the inner loop sets the six cells of row 0 to 0.jruns from 0 to 5.i = 1: row 1 is cleared.i = 2: row 2 is cleared.i = 3: row 3 is cleared.i = 4: row 4 is cleared.i = 5: the last row is cleared too. The loop ends: 6 × 6 = 36 cells were written.- Result: a graph with 6 vertices and no edges. Every cell is 0.
#define MAX 8 struct Graph { int n; // number of vertices bool directed; // true for a directed graph int adj[MAX][MAX]; // adj[u][v] = 1: there is an edge from u to v}; void create(struct Graph* g, int n, bool directed) { g->n = n; g->directed = directed; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) g->adj[i][j] = 0; // no edges at the start}class MatrixGraph { int n; // number of vertices boolean directed; // true for a directed graph int[][] adj; // adj[u][v] = 1: there is an edge from u to v MatrixGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new int[n][n]; // Java starts every cell at 0 }}class MatrixGraph: def __init__(self, n, directed=False): self.n = n # number of vertices self.directed = directed # True for a directed graph # every row is its own list; adj[u][v] = 1: edge from u to v self.adj = [[0] * n for _ in range(n)]The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Two nested loops write each of the n × n cells once.
The matrix holds n × n cells whatever the number of edges.
In a graph with few edges most cells stay 0 and the room is wasted. An adjacency list takes room only for the edges that exist; the comparison is in lesson 8.2.6.
4Common mistake
A common mistake in Python is building the matrix by multiplying a list:
self.adj = [[0] * n] * n # wrong: all n rows are the same listThis line builds one list and refers to it n times. Write adj[0][1] = 1 and cell 1 of every row becomes 1 at once, because they are all the same list. To build each row on its own, use the list comprehension in the code: for _ in range(n) makes a new row list on every turn. The similar mistake in C is not clearing the matrix in create at all: random values in a local variable look like edges.
5Try it
An undirected graph has an edge between 2 and 5. Which cells of the matrix are 1?
The answer is B. An undirected edge has no direction; you can go from 2 to 5 and from 5 to 2. So two cells become 1 and the matrix stays symmetric.
Show the answer
The answer is B. An undirected edge has no direction; you can go from 2 to 5 and from 5 to 2. So two cells become 1 and the matrix stays symmetric.
In C, with MAX equal to 8, how many cells does create(&g, 6, false) set to 0?
The answer is A. The loops run i and j from 0 to n - 1: 6 × 6 = 36 cells. The rest of the cells are not used.
Show the answer
The answer is A. The loops run i and j from 0 to n - 1: 6 × 6 = 36 cells. The rest of the cells are not used.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.