 The Adjacency matrix is a way to represent a graph using a matrix, where the rows and columns of the matrix represent the vertices of the graph. If there is an edge between two vertices, then the corresponding entry in the matrix is set to 1. Otherwise, it is set to 0.

An adjacency matrix in Java is a way to represent a graph using a two-dimensional array. In this representation, each row and column of the matrix represents a vertex in the graph, and the value at the intersection of the row and column indicates whether there is an edge between those vertices.

If the value is 1, it means that there is an edge between the vertices, while a value of 0 means that there is no edge. ### Matrix Representation of the above Graph

In this matrix, the row and column with index 0 represent vertex 1, the row and column with index 1 represent vertex 2, and so on. ### Example Implementation Using A HashMap:

Run
```import java.util.*;

public class Main{

public static void main(String[] args) {
// Create an adjacency matrix with 5 vertices

// Add edges to the matrix

for (int i = 0; i < adjacencyMatrix.length; i++) {
for (int j = 0; j < adjacencyMatrix[i].length; j++) {
}
System.out.println();
}
}
}
```

### Output

```0 1 0 0 0
1 0 1 0 0
0 1 0 1 0
0 0 1 0 1
0 0 0 1 0
```

### Explanation:

In the above example, we create a 5×5 adjacency matrix and add edges to it. Then we use two nested loops to print out the matrix row by row.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others