Adjacency Matrix

Java Adjacency Matrix

What is Adjacency Matrix?

In this Article, We will discuss about the Adjacency Matrix in Java.
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.

Adjacency Matrix:

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.

Java Adjacecncy Matrix

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.

Adjacency Matrix

Advantages to Use Adjacency Matrix

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
        int[][] adjacencyMatrix = new int[5][5];

        // Add edges to the matrix
        adjacencyMatrix[0][1] = 1;
        adjacencyMatrix[1][0] = 1;
        adjacencyMatrix[1][2] = 1;
        adjacencyMatrix[2][1] = 1;
        adjacencyMatrix[2][3] = 1;
        adjacencyMatrix[3][2] = 1;
        adjacencyMatrix[3][4] = 1;
        adjacencyMatrix[4][3] = 1;

        // Print the adjacency matrix
        for (int i = 0; i < adjacencyMatrix.length; i++) {
            for (int j = 0; j < adjacencyMatrix[i].length; j++) {
                System.out.print(adjacencyMatrix[i][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.

Prime Course Trailer

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription