Adjacency Matrix
Adjacency Matrix
When you study graphs, youโll often hear people say things like โWe need to store the connections between nodes.โ
A graph is basically a collection of points (called vertices) and lines between those points (called edges).
Now the question is:
How do we store this graph inside a computer in a neat and organized way?
One popular method is called the Adjacency Matrix.
Letโs understand it slowly and comfortably.
๐ฟ What Is an Adjacency Matrix?
Imagine you have a small group of friends: A, B, C, and D.
Sometimes you want to know who is connected to whom.
An adjacency matrix is like a friendship chart.
- It has a row for each vertex.
- It has a column for each vertex.
- Every cell tells whether two vertices share a connection.
We normally write:
- 1 โ if there is an edge
- 0 โ if there is no edge
Itโs that simple.
Itโs like marking Yes or No, but using numbers.
๐จ A Small Graph Example
Letโs take a tiny graph with 4 vertices:
(A) ----- (B)
| |
| |
(C) (D)
Connections:
- A โ B
- A โ C
- B โ D
- C and D are not connected
๐งพ Adjacency Matrix for This Graph
We list the vertices in order: A, B, C, D
Now create a 4ร4 grid:
A B C D
A 0 1 1 0
B 1 0 0 1
C 1 0 0 0
D 0 1 0 0
Why does AโA, BโB, CโC, DโD show 0?
Because a vertex usually doesnโt connect to itself.
Why does AโB show 1 and BโA also show 1?
Because this is an undirected graph, and connections work both ways.
If you go from A to B, you can also come back from B to A.
๐ก A Simple Analogy: Bus Routes
Think of each vertex as a bus stop.
The adjacency matrix is like a table telling which stops have direct buses between them.
- If there is a direct bus โ put 1
- If not โ put 0
This makes it easy to check connections quickly.
โก Why Is the Adjacency Matrix Useful?
โ Super fast checks
Want to know if C connects to A?
Just look at the cell (C, A).
In one step, you get the answer.
โ Easy for computers
Computers love tables.
They can jump to any cell instantly.
โ Great for dense graphs
If your graph has a lot of edges, the matrix becomes very helpful.
๐ฉ When Is It Not So Great?
Every graph with n vertices needs an n ร n matrix.
So if you have 1,000 vertices, you get a giant 1000ร1000 table.
Most of those cells may be zeros.
So adjacency matrices arenโt ideal for sparse graphs (graphs with few edges).
Also:
- Adding a new vertex means rebuilding the whole matrix.
- It uses a lot of memory when the graph is large.
