Java Program to Represent Graph Using 2D Arrays

This is a java program to represent graph as a 2D array. 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 2D Arrays. 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 two d array
import java.util.Scanner;
 
public class Represent_Graph_TwoD_Array 
{
    private final int vertices;
    private int[][] twoD_array;
 
    public Represent_Graph_TwoD_Array(int v) 
    {
        vertices = v;
        twoD_array = new int[vertices + 1][vertices + 1];
    }
 
    public void makeEdge(int to, int from, int edge) 
    {
        try 
        {
            twoD_array[to][from] = edge;
        }
        catch (ArrayIndexOutOfBoundsException index) 
        {
            System.out.println("The vertices does not exists");
        }
    }
 
    public int getEdge(int to, int from) 
    {
        try 
        {
            return twoD_array[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_TwoD_Array 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_TwoD_Array(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 two d array 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("Something went wrong");
        }
        sc.close();
    }
}

Output:

$ javac Represent_Graph_TwoD_Array.java
$ java Represent_Graph_TwoD_Array
 
Enter the number of vertices: 
4 
Enter the number of edges: 
5
Enter the edges: <to> <from>
1 2
2 3 
3 4
1 3
1 4
The two d array for the given graph is: 
  1 2 3 4 
1 0 1 1 1 
2 0 0 1 0 
3 0 0 0 1 
4 0 0 0 0

Related posts:

An Example of Load Balancing with Zuul and Eureka
Java Program to Implement the One Time Pad Algorithm
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Dockerizing a Spring Boot Application
Java Program to find the maximum subarray sum O(n^2) time(naive method)
Examine the internal DNS cache
Introduction to the Java NIO2 File API
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Constructor Dependency Injection in Spring
Convert Hex to ASCII in Java
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Implement Kosaraju Algorithm
Spring REST API + OAuth2 + Angular
Spring Data JPA @Query
XML Serialization and Deserialization with Jackson
Jackson Ignore Properties on Marshalling
Java Program to Implement Find all Forward Edges in a Graph
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Spring Data Java 8 Support
Java Program to Generate All Possible Combinations of a Given List of Numbers
Ép kiểu trong Java (Type casting)
Java Program to Implement Flood Fill Algorithm
Hashing a Password in Java
Java Program to Implement Solovay Strassen Primality Test Algorithm
Mockito and JUnit 5 – Using ExtendWith
Giới thiệu Google Guice – Dependency injection (DI) framework
Login For a Spring Web App – Error Handling and Localization
Java Program to Check Cycle in a Graph using Topological Sort
Java Program to Solve a Matching Problem for a Given Specific Case
Một số nguyên tắc, định luật trong lập trình
Spring WebFlux Filters
Spring @Primary Annotation