8.1Graph with an Adjacency Matrix
Neighbours and degree
Finding the neighbours of a vertex is the most common job on a graph: every traversal and graph algorithm keeps asking "who are this vertex's neighbours?". In an adjacency matrix the answer is in row u: the columns holding a 1 are the neighbours of u. This lesson writes four small functions: are two vertices adjacent, the degree, the in-degree and printing the neighbours.
- Telling whether two vertices are adjacent by looking at one cell
- That the degree is the number of 1s in a row and the in-degree the number in a column
- Why finding neighbours in a matrix always takes
nsteps
1The idea
hasEdge(g, u, v) only looks at cell adj[u][v]: O(1). The matrix has no rival here; an adjacency list has to scan a list to answer the same question.
degree(g, u) walks row u from start to end and counts the 1s; printNeighbors prints the numbers of the columns holding a 1 in the same loop. The columns are walked from 0 to n-1, so the neighbours come out from smallest to largest. This order will decide the order of the traversals in the BFS and DFS lessons.
In a directed graph the 1s in a row are the edges leaving the vertex, so degree gives the out-degree. The edges coming in are in the column: inDegree(g, v) counts column v from top to bottom. In an undirected graph the matrix is symmetric, so the two numbers are the same.
2Step by step
In the drawing printNeighbors(&g, 1) walks row 1 from left to right. The cell being checked is orange; the cells found to hold 1 and the neighbours printed are green. The output so far is shown under the drawing.
printNeighbors(&g, 1)is called. The neighbours of 1 are in row 1.v = 0:adj[1][0]is 1. 0 is printed. Output: 0.v = 1:adj[1][1]is 0. A vertex is not its own neighbour; skip.v = 2:adj[1][2]is 1. 2 is printed. Output: 0 2.v = 3:adj[1][3]is 0; skip.v = 4:adj[1][4]is 1. 4 is printed. Output: 0 2 4.v = 5:adj[1][5]is 0. The row is done; 6 cells were checked.- Result: the neighbours of 1 are 0, 2 and 4.
degree(&g, 1)returns 3 with the same loop.
#define MAX 8 struct Graph { int n; bool directed; int adj[MAX][MAX];}; bool hasEdge(struct Graph* g, int u, int v) { return g->adj[u][v] == 1;} int degree(struct Graph* g, int u) { int count = 0; for (int v = 0; v < g->n; v++) if (g->adj[u][v] == 1) count++; // the 1s in row u return count;} int inDegree(struct Graph* g, int v) { int count = 0; for (int u = 0; u < g->n; u++) if (g->adj[u][v] == 1) count++; // the 1s in column v return count;} void printNeighbors(struct Graph* g, int u) { for (int v = 0; v < g->n; v++) if (g->adj[u][v] == 1) printf("%d ", v);}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 hasEdge(int u, int v) { return adj[u][v] == 1; } int degree(int u) { int count = 0; for (int v = 0; v < n; v++) if (adj[u][v] == 1) count++; // the 1s in row u return count; } int inDegree(int v) { int count = 0; for (int u = 0; u < n; u++) if (adj[u][v] == 1) count++; // the 1s in column v return count; } void printNeighbors(int u) { for (int v = 0; v < n; v++) if (adj[u][v] == 1) System.out.print(v + " "); }}class MatrixGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [[0] * n for _ in range(n)] def has_edge(self, u, v): return self.adj[u][v] == 1 def degree(self, u): count = 0 for v in range(self.n): if self.adj[u][v] == 1: count += 1 # the 1s in row u return count def in_degree(self, v): count = 0 for u in range(self.n): if self.adj[u][v] == 1: count += 1 # the 1s in column v return count def print_neighbors(self, u): for v in range(self.n): if self.adj[u][v] == 1: print(v, end=" ")The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Finding the neighbours and counting the degree look at all n cells of the row, however many neighbours the vertex has. hasEdge is O(1).
Only a counter and the loop variable are used.
In a sparse graph n cells are scanned even when a vertex has 2 neighbours. Visiting the neighbours of every vertex takes O(n²) with a matrix; with lists it is O(n + e).
4Common mistake
A common mistake in a directed graph is counting the in-degree from the row:
for (int u = 0; u < g->n; u++) if (g->adj[v][u] == 1) // wrong: these are edges leaving v count++;adj[v][u] is the edge from v to u, an outgoing one. For the in-degree the target is the column: adj[u][v], with u from 0 to n-1. In an undirected graph both ways give the same answer, so the bug goes unnoticed until a directed graph is tried.
5Try it
In the matrix of a directed graph, column 2 holds four 1s and row 2 holds one 1. What are the in-degree and out-degree of vertex 2?
The answer is B. The 1s in a column are edges coming into the vertex: in-degree 4. Those in a row are edges going out: out-degree 1.
Show the answer
The answer is B. The 1s in a column are edges coming into the vertex: in-degree 4. Those in a row are edges going out: out-degree 1.
In a graph with 1000 vertices, vertex 7 has only 2 neighbours. How many cells does degree(&g, 7) look at?
The answer is B. The matrix does not know where the neighbours are; every cell of the row has to be checked: 1000 cells.
Show the answer
The answer is B. The matrix does not know where the neighbours are; every cell of the row has to be checked: 1000 cells.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.