How To Write Adjacency Matrix Java

6 min read

How to Write Adjacency Matrix in Java: A Complete Guide

Graphs are one of the most fundamental data structures in computer science, and understanding how to represent them in code is a critical skill for every programmer. Practically speaking, one of the most popular and intuitive ways to represent a graph is through an adjacency matrix. If you are learning data structures in Java or preparing for technical interviews, mastering the adjacency matrix implementation is a must. This guide walks you through everything you need to know — from the basic concept to a fully working Java program.


What Is an Adjacency Matrix?

An adjacency matrix is a two-dimensional array used to represent a finite graph. The matrix dimensions are V × V, where V is the total number of vertices (or nodes) in the graph. Each cell matrix[i][j] indicates whether there is an edge connecting vertex i to vertex j The details matter here. Still holds up..

For an unweighted, undirected graph, the values are typically:

  • 1 — if there is an edge between vertex i and vertex j
  • 0 — if there is no edge

For a weighted graph, the cell stores the actual weight of the edge instead of just 1 Not complicated — just consistent..

In a directed graph, matrix[i][j] = 1 means there is an edge from vertex i to vertex j, but not necessarily the reverse. In an undirected graph, the matrix is always symmetric, meaning matrix[i][j] = matrix[j][i].


Why Use an Adjacency Matrix in Java?

There are several reasons why the adjacency matrix is a go-to representation for many developers:

  • Simplicity: It is straightforward to understand and implement.
  • Fast edge lookup: Checking whether an edge exists between two vertices takes O(1) time.
  • Good for dense graphs: When the number of edges is close to the maximum possible, the adjacency matrix is very efficient.
  • Matrix operations: It enables the use of linear algebra techniques for graph algorithms.

That said, it is important to note that adjacency matrices are not ideal for sparse graphs (graphs with very few edges), because they consume O(V²) space regardless of the actual number of edges.


Step-by-Step: How to Write an Adjacency Matrix in Java

Follow these steps to build your adjacency matrix representation in Java That's the part that actually makes a difference..

Step 1: Define the Number of Vertices

Start by deciding how many vertices your graph will have. This determines the size of your 2D array Nothing fancy..

int vertices = 5;

Step 2: Create the 2D Array

Declare and initialize a two-dimensional integer array of size vertices × vertices. By default, all values will be 0 Which is the point..

int[][] adjacencyMatrix = new int[vertices][vertices];

Step 3: Add Edges to the Matrix

To add an edge between two vertices, set the corresponding cells to 1. For an undirected graph, you must update both matrix[i][j] and matrix[j][i].

// Add edge between vertex 0 and vertex 1
adjacencyMatrix[0][1] = 1;
adjacencyMatrix[1][0] = 1;

Step 4: Display the Matrix

Use nested loops to print the matrix and verify your graph structure.

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

Complete Java Program

Here is a fully working Java program that demonstrates how to write and display an adjacency matrix for an undirected, unweighted graph And it works..

public class AdjacencyMatrixExample {

    public static void main(String[] args) {

        // Step 1: Define the number of vertices
        int vertices = 5;

        // Step 2: Create the adjacency matrix
        int[][] adjacencyMatrix = new int[vertices][vertices];

        // Step 3: Add edges (undirected graph)
        addEdge(adjacencyMatrix, 0, 1);
        addEdge(adjacencyMatrix, 0, 4);
        addEdge(adjacencyMatrix, 1, 2);
        addEdge(adjacencyMatrix, 1, 3);
        addEdge(adjacencyMatrix, 1, 4);
        addEdge(adjacencyMatrix, 2, 3);
        addEdge(adjacencyMatrix, 3, 4);

        // Step 4: Display the adjacency matrix
        System.out.println("Adjacency Matrix:");
        printMatrix(adjacencyMatrix, vertices);
    }

    // Method to add an edge in an undirected graph
    public static void addEdge(int[][] matrix, int i, int j) {
        matrix[i][j] = 1;
        matrix[j][i] = 1;
    }

    // Method to print the matrix
    public static void printMatrix(int[][] matrix, int vertices) {
        for (int i = 0; i < vertices; i++) {
            for (int j = 0; j < vertices; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.

**Expected Output:**

Adjacency Matrix: 0 1 0 0 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 1 0


---

## Understanding the Code Step by Step

Let us break down what happens inside the program:

1. **Initialization**: A `5 × 5` matrix is created with all values set to `0`. This represents a graph with 5 vertices and no edges initially.
2. **Adding edges**: The `addEdge` method sets both `matrix[i][j]` and `matrix[j][i]` to `1`, ensuring the graph remains undirected. Take this: when you add an edge between vertex `0` and vertex `1`, both `matrix[0][1]` and `matrix[1][0]` become `1`.
3. **Printing**: The nested `for` loop iterates through every row and column, printing each value. Each row represents a vertex, and the `1`s in that row tell you which other vertices it is connected to.

---

## Common Operations on an Adjacency Matrix

Once you have your adjacency matrix, you can perform several useful operations efficiently:

- **Check if an edge exists**: Simply access `

- Check if an edge exists**: To determine whether there is a connection between two vertices, simply look at the corresponding entry in the matrix. If `adjacencyMatrix[i][j] == 1`, then a direct edge connects vertex `i` to vertex `j`. Since this implementation uses an undirected graph, both `adjacencyMatrix[i][j]` and `adjacencyMatrix[j][i]` will be equal to `1` whenever an edge is present.

- **Calculate vertex degree**: The degree of a vertex is the number of edges incident to it. In an adjacency matrix, this can be computed by summing up the entries in a single row (or equivalently, column). Here's one way to look at it: the degree of vertex `2` in our current graph would be calculated as `adjacencyMatrix[2][0] + adjacencyMatrix[2][1] + adjacencyMatrix[2][3] + adjacencyMatrix[2][4] = 0 + 1 + 1 + 0 = 2`.

- **Detect cycles**: While adjacency matrices are excellent for quick edge existence checks, detecting cycles typically requires additional algorithms such as Depth-First Search (DFS) or Breadth-First Search (BFS) on the underlying graph representation. Even so, once you have the adjacency list derived from the matrix, cycle detection becomes straightforward.

- **Use case applications**: Adjacency matrices are particularly well-suited for dense graphs where the number of edges approaches the maximum possible (`n²`). They allow for O(V²) time complexity for basic operations like edge lookup and space-efficient storage compared to adjacency lists when the graph is nearly complete. These properties make them ideal for scenarios involving frequent edge queries, such as network connectivity analysis, game theory problems, and solving systems of equations related to linear algebra.

---

### Conclusion

Simply put, the adjacency matrix is a powerful data structure for representing weighted or unweighted graphs, especially those that are dense. By initializing a square matrix of appropriate size and populating it based on defined edges, we can efficiently query the presence of connections between any pair of vertices. The provided Java program illustrates the core workflow—defining the graph size, adding edges while maintaining symmetry for undirected graphs, and displaying the resulting matrix. Beyond simple visualization, adjacency matrices serve as a foundation for more advanced graph algorithms and computational tasks, making them an indispensable tool in computer science and engineering. Whether you need to check connectivity, compute degrees, or explore deeper algorithmic techniques, mastering the use of adjacency matrices opens the door to efficient graph processing.
Just Came Out

Dropped Recently

Along the Same Lines

You Might Also Like

Thank you for reading about How To Write Adjacency Matrix Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home