# What Is Adjacency Matrix Give Example in Data Structure?

//

Larry Thompson

In the field of data structures, an adjacency matrix is a square matrix used to represent a graph. It is a powerful tool that helps in analyzing and manipulating graphs efficiently. In this article, we will delve into the concept of an adjacency matrix and provide an example to further solidify our understanding.

## What is an Adjacency Matrix?

An adjacency matrix is a two-dimensional array, commonly implemented as a matrix of boolean values or integers. It represents the connections between vertices in a graph. The rows and columns of the matrix correspond to the vertices of the graph, and each cell indicates whether there is an edge between two vertices.

In a directed graph, where edges have a specific direction, the adjacency matrix can be either symmetric or asymmetric. In an undirected graph, where edges have no direction, the adjacency matrix is always symmetric.

## Example:

Consider a simple undirected graph with 4 vertices labeled as A, B, C, and D. The following diagram visually represents the connections between these vertices:

```    A --- B
|     |
|     |
C --- D
```

To represent this graph using an adjacency matrix, we create a 4×4 matrix as follows:

```    | A | B | C | D |
---------------------
A   | 0 | 1 | 1 | 0 |
---------------------
B   | 1 | 0 | 0 | 1 |
---------------------
C   | 1 | 0 | 0 | 1 |
---------------------
D   | 0 | 1 | 1 | 0 |
```

The rows and columns of this matrix correspond to the vertices A, B, C, and D. The value at each cell indicates whether there is an edge between the corresponding vertices. In this example, a value of 1 represents the presence of an edge, while a value of 0 represents the absence of an edge.

For instance, cell (A, B) and cell (B, A) both have a value of 1, indicating that there is an edge between vertices A and B. Similarly, cell (C, D) and cell (D, C) both have a value of 1, representing the presence of an edge between vertices C and D.

• Efficient Edge Queries: The adjacency matrix allows for efficient queries about the existence or absence of edges between vertices.
• Easy Graph Traversal: Traversing a graph represented by an adjacency matrix is straightforward and can be done with simple loops.