Java Program to Describe the Representation of Graph using Adjacency Matrix

Java program to describe the representation of graph using adjacency matrix.In mathematics and computer science, an adjacency matrix is a means of representing which vertices (or nodes) of a graph are adjacent to which other vertices. Another matrix representation for a graph is the incidence matrix.

Here is source code of the Java program to find the adjacency matrix of a given graph .The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

import java.util.InputMismatchException;
import java.util.Scanner;
 
public class GraphAdjacencyMatrix
{
    private final int MAX_NO_OF_VERTICES;
    private int adjacency_matrix[][];
 
    public GraphAdjacencyMatrix(int number_of_vertices)
    {
        MAX_NO_OF_VERTICES = number_of_vertices;
        adjacency_matrix = new int[MAX_NO_OF_VERTICES + 1][MAX_NO_OF_VERTICES + 1];
    }
 
    public void setEdge(int from_vertex, int to_vertex, int edge) 
    {
        try 
        {
            adjacency_matrix[from_vertex][to_vertex] = edge;
        } catch (ArrayIndexOutOfBoundsException indexBounce)
        {
            System.out.println("the vertex entered is not present");
        }
    }
 
    public int getEdge(int from_vertex, int to_vertex)
    {
        try 
        {
            return adjacency_matrix[from_vertex][to_vertex];
        } catch (ArrayIndexOutOfBoundsException indexBounce)
        {
            System.out.println("the vertex entered is not present")
        }
        return -1;
    }
 
    public static void main(String... arg) 
    {
        int number_of_vertices, count = 1;
        int source = 0, destination = 0;
        Scanner scan = new Scanner(System.in);
        GraphAdjacencyMatrix adjacencyMatrix;
 
        try 
        {  
            System.out.println("Enter the Number of Vertices");
            number_of_vertices = scan.nextInt();
            System.out.println("Enter the Number of Edges"); 
            int number_of_edges = scan.nextInt();
            adjacencyMatrix = new GraphAdjacencyMatrix(number_of_vertices);
 
            System.out.println("Enter The Graph Egdes :<source> <destination>");
            while (count <= number_of_edges)
            {
                source = scan.nextInt();
                destination = scan.nextInt();
                adjacencyMatrix.setEdge(source, destination, 1);
                count++;
            }
            System.out.println("The adjacency matrix for given graph is");
            for (int i = 1; i <= number_of_vertices; i++)
                System.out.print(i);
 
            System.out.println();
            for (int i = 1; i <= number_of_vertices; i++) 
            {
                System.out.print(i);
                for (int j = 1; j <= number_of_vertices; j++)
                { 
                    System.out.print(adjacencyMatrix.getEdge(i, j));
                } 
                System.out.println();
            }
        } catch (InputMismatchException inputMisMatch) 
        {
            System.out.println("Error in Input Format.<source index> <destination index>");
        }
        scan.close();
    }
}
$javac GraphAdjacencyMatrix.java
$java GraphAdjacencyMatrix
 
Enter the Number of Vertices and Edges
4 5
Enter The Graph Egdes Format : <source index> <destination index> 
 
1 2 
2 3
3 4
4 1
1 3
 
The adjacency matrix for given graph is 
 
	1	2	3	4
1	0	1	1	0	
2	0	0	1	0	
3	0	0	0	1	
4	1	0	0	0

Related posts:

Introduction to Using FreeMarker in Spring MVC
JUnit 5 @Test Annotation
The HttpMediaTypeNotAcceptableException in Spring MVC
Creating a Custom Starter with Spring Boot
A Guide to the finalize Method in Java
Spring MVC Async vs Spring WebFlux
Spring Boot - Admin Server
Java Program to Implement Cartesian Tree
Java Program to Perform Finite State Automaton based Search
Spring 5 WebClient
Java Program to Represent Graph Using Incidence Matrix
Instance Profile Credentials using Spring Cloud
New Features in Java 14
Java Program to Implement Pagoda
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Hướng dẫn Java Design Pattern – State
Error Handling for REST with Spring
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
HttpClient Basic Authentication
Java Program to Implement Splay Tree
Giới thiệu Google Guice – Injection, Scope
HttpClient 4 – Follow Redirects for POST
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Giới thiệu Json Web Token (JWT)
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Derived Query Methods in Spring Data JPA Repositories
Java Program to Construct an Expression Tree for an Infix Expression
Java Program to Implement Cubic convergence 1/pi Algorithm
Bootstrap a Web Application with Spring 5
Generate Spring Boot REST Client with Swagger