Quiz 2
Registry Synced

Week 7: Adjacency Matrices

1472 words
7 min read

Reading compass

Now · 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 relationshipsMatrices store relationships between every pair
Finding if two items are related requires scanMatrix gives O(1) answer: M[i][j]
Can't easily aggregate relationship dataRow/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:
sql
M[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

pseudo
Procedure 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

sql
mymatrix = 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:
pseudo
    0  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

sql
outDegree = {}
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

pseudo
inDegree = {}
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

PropertyMeaning
SizeN × N for N vertices
DiagonalM[i][i] is usually 0 (no self-loops)
SymmetricM[i][j] = M[j][i] for undirected graphs
Row i sumOutgoing degree of vertex i
Column j sumIncoming degree of vertex j
1-normTotal edges = sum of all entries

Undirected vs Directed

Undirected graph (friendship):
pseudo
    A 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):
sql
    A 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

pseudo
Procedure 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

pseudo
Procedure 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

pseudo
Procedure 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)

pseudo
Procedure 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

pseudo
Procedure 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

AspectAdjacency MatrixAdjacency List
SpaceO(N²)O(N + E)
Check edgeO(1)O(degree)
Find all neighborsO(N)O(degree)
Add edgeO(1)O(1)
Remove edgeO(1)O(degree)
Best forDense graphs (many edges)Sparse graphs (few edges)
ImplementationNested dictionariesDictionary of lists

Which to Use?

In this course, we always use nested dictionaries (matrix form) because:
  1. Simple to create and access
  2. The graphs we work with are often dense (many edges)
  3. Matrix operations (transitive closure, shortest paths) are straightforward

10. Practice Questions

Basic Questions

Q1. What is an adjacency matrix?
Show Answer
An 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 Answer
6 × 6 = 36 entries. The diagonal is usually 0. Q3. What does a symmetric matrix indicate about a graph? Show Answer
A 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 Answer
Sum 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 Answer
pseudo
mat = 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 Answer
Students 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:
pseudo
    A B C
A  [0,1,1]
B  [0,0,1]
C  [0,0,0]
Show Answer
Edges: (A→B), (A→C), (B→C) = 3 directed edges.

📚 Cross-References

CourseTopicConnection
BSCS2002 (PDSA)Week 7 — GraphsMatrix representation
BSCS2002 (PDSA)Week 8 — PathsMatrix multiplication for paths

Quiz Tip: Understand how to read and construct adjacency matrices. Know the difference between directed and undirected! Join Discord PreviousGraphs & Adjacency MatricesNextGraph Algorithms — Routes & Paths
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.