8.1Graph with an Adjacency Matrix
Adding and removing edges
Right after the matrix is set up the graph is empty: every cell is 0. Adding an edge means writing 1 into its cell; removing it means writing 0 again. No loop, no shifting: the strong point of an adjacency matrix is that the place of an edge is found directly from two indexes.
- Which cells change when you add or remove an edge
- Why an undirected graph writes two cells and a directed one a single cell
- How a bad vertex, an edge to itself and a repeated edge are refused
1The idea
addEdge(g, u, v) first checks that both vertices are between 0 and n-1. If u == v it refuses: an edge from a vertex to itself (a self-loop) does not exist in the graphs of this part. If the edge is already there it also returns false, so the same edge is never counted twice. Then adj[u][v] becomes 1.
If the graph is undirected, adj[v][u] becomes 1 as well, because the edge works both ways and the matrix must stay symmetric. In a directed graph only the cell from u to v is written; the opposite cell stands for a different edge.
removeEdge makes the same checks and sets the cells back to 0. If the edge is not there it returns false. Both operations touch only one or two cells; however big the graph, the time stays the same.
In a weighted graph the cell holds the weight of the edge instead of 1, and a missing edge is marked with a value that cannot be a weight (0 or infinity).
2Step by step
The drawing adds the edges of the sample graph to an empty matrix one by one. u and v are the two ends of the edge; the cells that change are orange. At the end two bad requests are refused and one edge is removed.
- Start: an empty graph with 6 vertices. Every cell is 0.
addEdge(&g, 0, 1). Both vertices are valid and the edge is not there.adj[0][1] = 1.- The graph is undirected, so
adj[1][0] = 1is written too. 0 and 1 are now neighbours. addEdge(&g, 0, 3):adj[0][3]andadj[3][0]become 1.addEdge(&g, 1, 2):adj[1][2]andadj[2][1].addEdge(&g, 1, 4):adj[1][4]andadj[4][1].addEdge(&g, 2, 5):adj[2][5]andadj[5][2].addEdge(&g, 3, 4):adj[3][4]andadj[4][3].addEdge(&g, 4, 5): the seventh edge. The matrix holds 14 = 2 × 7 ones and is symmetric about its diagonal.addEdge(&g, 2, 2):u == v, an edge to itself. It returns false and the matrix does not change.addEdge(&g, 0, 1)a second time:adj[0][1]is already 1. It returns false.removeEdge(&g, 1, 4):adj[1][4]andadj[4][1]are 0 again. The edge is gone from the graph.- Result: 6 vertices and 6 edges. Each operation touched only two cells.
#define MAX 8 struct Graph { int n; bool directed; int adj[MAX][MAX];}; bool addEdge(struct Graph* g, int u, int v) { if (u < 0 || u >= g->n || v < 0 || v >= g->n || u == v) return false; // bad vertex or an edge to itself if (g->adj[u][v] == 1) return false; // the edge is already there g->adj[u][v] = 1; if (!g->directed) g->adj[v][u] = 1; // undirected: both ways return true;} bool removeEdge(struct Graph* g, int u, int v) { if (u < 0 || u >= g->n || v < 0 || v >= g->n) return false; if (g->adj[u][v] == 0) return false; // there is no such edge g->adj[u][v] = 0; if (!g->directed) g->adj[v][u] = 0; return true;}class MatrixGraph { int n; boolean directed; int[][] adj; MatrixGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new int[n][n]; } boolean addEdge(int u, int v) { if (u < 0 || u >= n || v < 0 || v >= n || u == v) return false; // bad vertex or an edge to itself if (adj[u][v] == 1) return false; // the edge is already there adj[u][v] = 1; if (!directed) adj[v][u] = 1; // undirected: both ways return true; } boolean removeEdge(int u, int v) { if (u < 0 || u >= n || v < 0 || v >= n) return false; if (adj[u][v] == 0) return false; // there is no such edge adj[u][v] = 0; if (!directed) adj[v][u] = 0; return true; }}class MatrixGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [[0] * n for _ in range(n)] def add_edge(self, u, v): if not (0 <= u < self.n and 0 <= v < self.n) or u == v: return False # bad vertex or an edge to itself if self.adj[u][v] == 1: return False # the edge is already there self.adj[u][v] = 1 if not self.directed: self.adj[v][u] = 1 # undirected: both ways return True def remove_edge(self, u, v): if not (0 <= u < self.n and 0 <= v < self.n): return False if self.adj[u][v] == 0: return False # there is no such edge self.adj[u][v] = 0 if not self.directed: self.adj[v][u] = 0 return TrueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The checks and writing two cells take constant time; it does not depend on n.
No new memory is taken; the matrix already holds n × n cells.
In an adjacency list adding an edge means searching for the neighbour's place in the list, which takes as long as the degree of the vertex. In a matrix the place of the edge is ready.
4Common mistake
The most common mistake in an undirected graph is writing the edge into one cell only:
g->adj[u][v] = 1; // adj[v][u] forgottenThen v shows up in the row of u, but u does not show up in the row of v. A traversal starting at v may never reach u, and the degrees come out wrong. The matrix of an undirected graph must always be symmetric: adj[u][v] == adj[v][u]. Writing without checking the bounds is a mistake too: in C, u = 8 writes outside the matrix and spoils another variable.
5Try it
In a directed graph, which cell does addEdge(&g, 3, 1) change?
The answer is B. In a directed graph the edge goes only from 3 to 1. The row is the source and the column the target: adj[3][1].
Show the answer
The answer is B. In a directed graph the edge goes only from 3 to 1. The row is the source and the column the target: adj[3][1].
Is there a difference in time between adding an edge to a graph with 10 vertices and to one with 1000 vertices?
The answer is A. The operation only writes cells adj[u][v] and adj[v][u]. The place of a cell is computed directly from two indexes.
Show the answer
The answer is A. The operation only writes cells adj[u][v] and adj[v][u]. The place of a cell is computed directly from two indexes.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.