Create Graph using Adjacency matrix in java

     Adjacency matrix is used to represent a graph. Generally, it uses two-dimensional array for storing the value. If there is a edge between the vertex x and y, it stores the value 1. Otherwise, it stores 0 value.

Java implementation:

Class: GraphAdjacencyMatrixEg

Member variables:

adj_matrix(integer array) , g_vertices(int),src(int), dest(int),

Objects: s1(Scanner object), g1(Graph object)

member functions:

Constructor : Initialise the values

‘addItEdge()’ : It assigns the edge value.

‘display()’ : It prints the adjacency matrix.

‘main()’ : it creates the scanner object and class object.

                 It gets the edge and vertex values and connectivity between vertices.

                 Call the the addItEdge and display functions to get the output.

Program:

import java.util.Scanner;

public class GraphAdjacencyMatrixEg {

    private int[][] adj_Matrix;

    private int g_vertices;

    public GraphAdjacencyMatrixEg(int g_vertices) {

        this.g_vertices = g_vertices;

        adj_Matrix = new int[g_vertices][g_vertices];

    }

    public void addItEdge(int src, int dest) {

        adj_Matrix[src][dest] = 1;

        adj_Matrix[dest][src] = 1; // it is an undirected graph

    }

    public void display() {

        System.out.println("The Adjacency Matrix:");

        for (int i = 0; i < g_vertices; i++) {

            for (int j = 0; j < g_vertices; j++) {

                System.out.print(adj_Matrix[i][j] + " ");

            }

            System.out.println();

        }

    }

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");

        int g_vertices = s1.nextInt();

        GraphAdjacencyMatrixEg g1 = new GraphAdjacencyMatrixEg(g_vertices);

        System.out.print("Enter the number of edges: ");

        int edges = s1.nextInt();

        System.out.println("Enter the edges in this order like (source destination):");

        for (int i = 0; i < edges; i++) {

            int src = s1.nextInt();

            int dest = s1.nextInt();

            g1.addItEdge(src, dest);

        }

        g1.display();

        s1.close();

    }

}

Output:

C:\raji\blog>javac GraphAdjacencyMatrixEg.java

C:\raji\blog>java GraphAdjacencyMatrixEg

Enter the number of vertices: 4

Enter the number of edges: 4

Enter the edges in this order like (source destination):

0 1

1 2

2 3

3 2

The Adjacency Matrix:

0 1 0 0

1 0 1 0

0 1 0 1

0 0 1 0

That’s all . The java implementation of Graph using adjacency matrix is done. Keep coding!!!

No comments:

Post a Comment