Week 7: Adjacency Matrices
1472 words
7 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Week 7: Adjacency Matrices > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Topic 13 (Graphs Introduction), Topic 11 (Dictionaries) **Cross-links:** BSCS2002-PDSA (Week 7 — Graph Representations) ## 1. Motivation: Why Matrices?

Week 7: Adjacency Matrices
BSCS1001 — IIT Madras BS Degree Prerequisite: Topic 13 (Graphs Introduction), Topic 11 (Dictionaries) Cross-links: BSCS2002-PDSA (Week 7 — Graph Representations)
1. Motivation: Why Matrices?
A graph describes relationships between entities. The most natural way to store a graph in our pseudocode is a matrix — a 2D table where each cell says whether two vertices are connected.
| Why Not Just a List? | Why a Matrix? |
|---|---|
| Lists store items, not relationships | Matrices store relationships between every pair |
| Finding if two items are related requires scan | Matrix gives O(1) answer: M[i][j] |
| Can't easily aggregate relationship data | Row/column sums give degree, popularity |
2. What is a Matrix?
A matrix is a two-dimensional table with rows and columns.
Matrix Notation
For a graph with N vertices, the adjacency matrix M is N × N:
sqlM[i][j] = 1 → Edge from vertex i to vertex j M[i][j] = 0 → No edge from i to j
Visual Example
(Diagram)
3. Creating Matrices with Nested Dictionaries
CreateMatrix Procedure
pseudoProcedure CreateMatrix(rows, cols) mat = {} i = 0 while (i < rows) { mat[i] = {} j = 0 while (j < cols) { mat[i][j] = 0 j = j + 1 } i = i + 1 } return(mat) End CreateMatrix
Example: Creating a 3×3 Matrix
sqlmymatrix = CreateMatrix(3, 3) mymatrix[0][1] = 1 // Set edge from 0 to 1 mymatrix[1][2] = 1 // Set edge from 1 to 2 mymatrix[0][2] = 1 // Set edge from 0 to 2
Result:
pseudo0 1 2 0 [0, 1, 1] 1 [0, 0, 1] 2 [0, 0, 0]
Mapping Names to Indices
When vertices have names (not numbers), we need an index mapping:
pseudo// Collect unique names allStudents = [] while (Pile 1 has more cards) { Pick X allStudents = allStudents ++ [X.Name] } // Create name → index mapping nameToIdx = {} i = 0 foreach name in allStudents { nameToIdx[name] = i i = i + 1 } // Create graph using indices n = length(allStudents) graph = CreateMatrix(n, n) graph[nameToIdx["Alice"]][nameToIdx["Bob"]] = 1
4. Row-Wise and Column-Wise Processing
Iterating Through a Matrix
pseudo// Row-wise (standard) foreach r in rows(mymatrix) { foreach c in columns(mymatrix) { // Process mymatrix[r][c] } } // Column-wise foreach c in columns(mymatrix) { foreach r in rows(mymatrix) { // Process mymatrix[r][c] } }
Row Sum = Outgoing Degree
sqloutDegree = {} foreach i in rows(graph) { count = 0 foreach j in columns(graph) { if (graph[i][j] == 1) { count = count + 1 } } outDegree[i] = count // How many edges FROM i }
Column Sum = Incoming Degree
pseudoinDegree = {} foreach j in columns(graph) { count = 0 foreach i in rows(graph) { if (graph[i][j] == 1) { count = count + 1 } } inDegree[j] = count // How many edges TO j }
5. Adjacency Matrix Properties
Key Properties
| Property | Meaning |
|---|---|
| Size | N × N for N vertices |
| Diagonal | M[i][i] is usually 0 (no self-loops) |
| Symmetric | M[i][j] = M[j][i] for undirected graphs |
| Row i sum | Outgoing degree of vertex i |
| Column j sum | Incoming degree of vertex j |
| 1-norm | Total edges = sum of all entries |
Undirected vs Directed
Undirected graph (friendship):
pseudoA B C A [0,1,1] // A-B, A-C B [1,0,1] // B-A, B-C C [1,1,0] // C-A, C-B // Symmetric!
Directed graph (mentoring):
sqlA B C A [0,1,1] // A→B, A→C B [0,0,1] // B→C (but not C→B) C [0,0,0] // No outgoing from C // Not symmetric
6. Similarity Graph
Problem
Two students are similar if their marks differ by at most 10 in ALL subjects.
Algorithm
pseudoProcedure CreateSimilarityGraph(marks1, marks2, marks3) n = length(keys(marks1)) similarityGraph = CreateMatrix(n, n) foreach i in keys(marks1) { foreach j in keys(marks1) { diff1 = abs(marks1[i] - marks1[j]) diff2 = abs(marks2[i] - marks2[j]) diff3 = abs(marks3[i] - marks3[j]) if (diff1 ≤ 10 AND diff2 ≤ 10 AND diff3 ≤ 10) { similarityGraph[i][j] = 1 } } } return(similarityGraph) End CreateSimilarityGraph
Properties
- Symmetric: If i is similar to j, then j is similar to i
- Reflexive: (Optionally) i is similar to itself
- Cliques: Groups where all are similar form cliques
7. Mentoring Graph Revisited
With Matrix Representation
pseudoProcedure CreateMentorGraph(marks) n = length(keys(marks)) mentorGraph = CreateMatrix(n, n) foreach i in keys(marks) { foreach j in keys(marks) { diff = marks[i] - marks[j] if (10 ≤ diff AND diff ≤ 20) { mentorGraph[i][j] = 1 // i can mentor j } } } return(mentorGraph) End CreateMentorGraph
Finding Mutual Mentoring Pairs
pseudo// i and j can be study partners if: // i mentors j in Maths AND j mentors i in Physics studyPairs = [] foreach i in rows(mathMentor) { foreach j in columns(mathMentor) { if (mathMentor[i][j] == 1 AND phyMentor[j][i] == 1) { studyPairs = studyPairs ++ [(i, j)] } } }
8. Matrix Operations
Copy a Matrix
pseudoProcedure CopyMatrix(mat) n = length(keys(mat)) newMat = CreateMatrix(n, n) foreach i in rows(mat) { foreach j in columns(mat) { newMat[i][j] = mat[i][j] } } return(newMat) End CopyMatrix
Transpose (Swap Rows and Columns)
pseudoProcedure Transpose(mat) n = length(keys(mat)) result = CreateMatrix(n, n) foreach i in rows(mat) { foreach j in columns(mat) { result[j][i] = mat[i][j] } } return(result) End Transpose
Add Two Matrices
pseudoProcedure AddMatrices(A, B) n = length(keys(A)) result = CreateMatrix(n, n) foreach i in rows(A) { foreach j in columns(A) { // Boolean OR for adjacency result[i][j] = A[i][j] OR B[i][j] } } return(result) End AddMatrices
9. Comparison: Matrix vs List Representations
| Aspect | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space | O(N²) | O(N + E) |
| Check edge | O(1) | O(degree) |
| Find all neighbors | O(N) | O(degree) |
| Add edge | O(1) | O(1) |
| Remove edge | O(1) | O(degree) |
| Best for | Dense graphs (many edges) | Sparse graphs (few edges) |
| Implementation | Nested dictionaries | Dictionary of lists |
Which to Use?
In this course, we always use nested dictionaries (matrix form) because:
- Simple to create and access
- The graphs we work with are often dense (many edges)
- Matrix operations (transitive closure, shortest paths) are straightforward
10. Practice Questions
Basic Questions
Q1. What is an adjacency matrix?
Show AnswerAn adjacency matrix is an N×N table where M[i][j] = 1 if there is an edge from vertex i to vertex j, and 0 otherwise. It represents a graph's connectivity. Q2. How big is the adjacency matrix for a graph with 6 vertices? Show Answer6 × 6 = 36 entries. The diagonal is usually 0. Q3. What does a symmetric matrix indicate about a graph? Show AnswerA symmetric matrix (M[i][j] = M[j][i]) indicates an undirected graph — if there's an edge from i to j, there's also an edge from j to i. Q4. How do you find the number of outgoing edges from vertex i? Show AnswerSum row i:count = 0; foreach j in columns(graph) { if graph[i][j] == 1 → count++ }
Intermediate Questions
Q5. Write pseudocode to create a 4×4 matrix with 0s on diagonal and 1s everywhere else (a complete graph).
Show Answerpseudomat = CreateMatrix(4, 4) foreach i in rows(mat) { foreach j in columns(mat) { if (i ≠ j) { mat[i][j] = 1 } } }
Q6. What is the difference between row-wise and column-wise processing?
Show Answer
- Row-wise: Outer loop over rows, inner loop over columns. Processes each vertex's outgoing edges.
- Column-wise: Outer loop over columns, inner loop over rows. Processes each vertex's incoming edges.
For undirected graphs, both give the same result. For directed graphs, they differ. Q7. In the similarity graph, why is the condition checked for ALL three subjects? Show AnswerStudents are similar only if their marks differ by at most 10 in every subject. If we only checked one or two subjects, we might incorrectly label students as similar when they have very different marks in the unchecked subject. Q8. Convert this matrix into a list of edges:
pseudoA B C A [0,1,1] B [0,0,1] C [0,0,0]
Show AnswerEdges: (A→B), (A→C), (B→C) = 3 directed edges.
📚 Cross-References
| Course | Topic | Connection |
|---|---|---|
| BSCS2002 (PDSA) | Week 7 — Graphs | Matrix representation |
| BSCS2002 (PDSA) | Week 8 — Paths | Matrix multiplication for paths |
Next Topic: 14 — Graph Algorithms — Routes & PathsQuiz Tip: Understand how to read and construct adjacency matrices. Know the difference between directed and undirected! Join Discord PreviousGraphs & Adjacency MatricesNextGraph Algorithms — Routes & Paths