Java Program to Represent Graph Using Adjacency Matrix

This is a java program to represent graph as a adjacency matrix. Nodes are arranged in matrix and at an index of i, j zero is displayed if nodes i and j are not connected, one otherwise.

Here is the source code of the Java Program to Represent Graph Using Adjacency Matrix. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

//This is a java program to represent graph as a adjacency matrix
import java.util.Scanner;
 
public class Represent_Graph_Adjacency_Matrix 
{
    private final int vertices;
    private int[][] adjacency_matrix;
 
    public Represent_Graph_Adjacency_Matrix(int v) 
    {
        vertices = v;
        adjacency_matrix = new int[vertices + 1][vertices + 1];
    }
 
    public void makeEdge(int to, int from, int edge) 
    {
        try 
        {
            adjacency_matrix[to][from] = edge;
        }
        catch (ArrayIndexOutOfBoundsException index) 
        {
            System.out.println("The vertices does not exists");
        }
    }
 
    public int getEdge(int to, int from) 
    {
        try 
        {
            return adjacency_matrix[to][from];
        }
        catch (ArrayIndexOutOfBoundsException index) 
        {
            System.out.println("The vertices does not exists");
        }
        return -1;
    }
 
    public static void main(String args[]) 
    {
        int v, e, count = 1, to = 0, from = 0;
        Scanner sc = new Scanner(System.in);
        Represent_Graph_Adjacency_Matrix graph;
        try 
        {
            System.out.println("Enter the number of vertices: ");
            v = sc.nextInt();
            System.out.println("Enter the number of edges: ");
            e = sc.nextInt();
 
            graph = new Represent_Graph_Adjacency_Matrix(v);
 
            System.out.println("Enter the edges: <to> <from>");
            while (count <= e) 
            {
                to = sc.nextInt();
                from = sc.nextInt();
 
                graph.makeEdge(to, from, 1);
                count++;
            }
 
            System.out.println("The adjacency matrix for the given graph is: ");
            System.out.print("  ");
            for (int i = 1; i <= v; i++)
                System.out.print(i + " ");
            System.out.println();
 
            for (int i = 1; i <= v; i++) 
            {
                System.out.print(i + " ");
                for (int j = 1; j <= v; j++) 
                    System.out.print(graph.getEdge(i, j) + " ");
                System.out.println();
            }
 
        }
        catch (Exception E) 
        {
            System.out.println("Somthing went wrong");
        }
 
        sc.close();
    }
}

Output:

$ javac Represent_Graph_Adjacency_Matrix.java
$ java Represent_Graph_Adjacency_Matrix
 
Enter the number of vertices: 
5
Enter the number of edges: 
7
Enter the edges: <to> <from>
1 1
2 3
3 4
4 5
3 5
1 4
2 4
The adjacency matrix for the given graph is: 
  1 2 3 4 5 
1 1 0 0 1 0 
2 0 0 1 1 0 
3 0 0 0 1 1 
4 0 0 0 0 1 
5 0 0 0 0 0

Related posts:

CharSequence vs. String in Java
Java Program to Implement Direct Addressing Tables
Immutable Objects in Java
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Find Transpose of a Graph Matrix
Java Program to Check Whether Graph is DAG
Java Program to Find a Good Feedback Edge Set in a Graph
Java Program to Perform the Shaker Sort
Spring WebClient and OAuth2 Support
Logout in an OAuth Secured Application
The Order of Tests in JUnit
Spring Boot - OAuth2 with JWT
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Guide to CopyOnWriteArrayList
Validate email address exists or not by Java Code
Java Program to Implement Binomial Heap
Extract links from an HTML page
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Implement Interpolation Search Algorithm
Java Program to Generate Random Hexadecimal Byte
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Quick Guide on Loading Initial Data with Spring Boot
Java Program to Implement TreeMap API
Getting Started with Forms in Spring MVC
Giới thiệu về Stream API trong Java 8
How to Read a Large File Efficiently with Java
Updating your Password
Thao tác với tập tin và thư mục trong Java
Lập trình đa luồng với Callable và Future trong Java
Java Program to Perform Complex Number Multiplication
Java Program to Print only Odd Numbered Levels of a Tree