Adjacency Matrix
About
An Adjacency Matrix is a 2D array representation of a graph where:
Rows and columns represent vertices.
Each cell (i, j) contains 1 (or weight) if there is an edge from vertex i to vertex j, otherwise 0.
Why Use an Adjacency Matrix?
Fast Edge Lookup: Checking if an edge exists is O(1).
Best for Dense Graphs: If the graph has many edges, adjacency matrices are efficient.
Easier Implementation: Simple 2D array structure.
Structure of an Adjacency Matrix
An adjacency matrix consists of:
A 2D array
graph[V][V], whereVis the number of vertices.If the graph is undirected,
graph[i][j] = graph[j][i].If the graph is weighted, the matrix stores weights instead of 1s.
Representation
For a graph with 4 vertices (V = 4) and edges (0→1, 0→2, 1→3, 2→3):
0
0
1
1
0
1
1
0
0
1
2
1
0
0
1
3
0
1
1
0
1. Graph Representation Using a 2D Array
Code
Output
Operations Breakdown and Time Complexity
Add Edge
O(1)
Directly updates the adjacency matrix.
Remove Edge
O(1)
Directly removes the edge from the matrix.
Check Edge
O(1)
Looks up value in matrix.
Get Neighbours
O(V)
Scans row in matrix to find connected vertices.
DFS Traversal
O(V²)
In the worst case, visits every vertex and edge.
BFS Traversal
O(V²)
Uses queue, but still needs to check matrix for neighbours.
2. Weighted Graph Implementation
If the graph is weighted, we replace 1 with the weight of the edge.
Code
Output
Operations Breakdown and Time Complexity
Add Edge
O(1)
Directly updates the adjacency matrix.
Remove Edge
O(1)
Directly removes the edge from the matrix.
Check Edge
O(1)
Looks up value in matrix.
Get Edge Weight
O(1)
Directly accesses weight from matrix.
Get Neighbors
O(V)
Scans row in matrix to find connected vertices.
DFS Traversal
O(V²)
Worst-case visits all vertices and edges.
BFS Traversal
O(V²)
Uses queue, but still checks matrix for neighbors.
Last updated