In graph theory, an Adjacency Matrix is a square matrix used to represent a graph. It provides a way of encoding the structure of a graph, where each element of the matrix indicates whether pairs of vertices are adjacent (connected) or not in the graph. The adjacency matrix is a powerful and widely used representation for both directed and undirected graphs, making it suitable for various applications, such as finding shortest paths, connectivity, and performing graph traversal.
An Adjacency Matrix is a 2D array (or matrix) used to represent a graph. The size of the matrix is , where is the number of vertices in the graph. The elements of the matrix indicate whether a pair of vertices is connected by an edge.
For a graph with vertices, the adjacency matrix is an matrix where:
In an undirected graph, the adjacency matrix is symmetric, meaning if there's an edge between vertex and vertex , the matrix has equal values at and .
Example:
Consider the undirected graph:
A - B
| |
C - D
The adjacency matrix for this graph would look like this:
A | B | C | D | |
---|---|---|---|---|
A | 0 | 1 | 1 | 0 |
B | 1 | 0 | 0 | 1 |
C | 1 | 0 | 0 | 1 |
D | 0 | 1 | 1 | 0 |
In a directed graph, the adjacency matrix is not necessarily symmetric. If there is an edge from vertex to vertex , then only , and the reverse remains 0 (unless there’s also an edge in that direction).
Example:
Consider the directed graph:
A → B
↓ ↑
C → D
The adjacency matrix for this directed graph would look like this:
A | B | C | D | |
---|---|---|---|---|
A | 0 | 1 | 1 | 0 |
B | 0 | 0 | 0 | 1 |
C | 0 | 0 | 0 | 1 |
D | 0 | 0 | 0 | 0 |
Check if an Edge Exists: To check if there is an edge from vertex to vertex , simply check if (or the edge weight if the graph is weighted). This operation takes time.
Add an Edge: To add an edge from vertex to vertex , set (or the edge weight). This operation also takes time.
Remove an Edge: To remove an edge between vertices and , set . This operation also takes time.
Get All Neighbors of a Vertex: To get all neighbors of a vertex , scan the -th row to find all columns where . This operation takes time.
Here’s how to represent a graph using an adjacency matrix in Python:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.matrix = [[0] * vertices for _ in range(vertices)]
def add_edge(self, u, v):
self.matrix[u][v] = 1 # For a directed graph
# For undirected graph, also set matrix[v][u] = 1
# self.matrix[v][u] = 1
def remove_edge(self, u, v):
self.matrix[u][v] = 0
def display(self):
for row in self.matrix:
print(row)
# Example usage
g = Graph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
print("Adjacency Matrix of the Graph:")
g.display()
Output:
Adjacency Matrix of the Graph:
[0, 1, 1, 0]
[0, 0, 0, 1]
[0, 0, 0, 1]
[0, 0, 0, 0]