Graph Representation using Adjacency Matrix - The Coding Shala

Home >> Data Structures >> Graph Representation using Adjacency Matrix

Graph Representation using Adjacency Matrix

In this post, we will see how to represent a graph using the Adjacency Matrix. Generally, the Adjacency matrix is used to check if there is any edge available between two vertices or not. In the Adjacency matrix, we take a 2D array of size v*V, where V is the number of vertices in a graph and array[i][j] = 1 indicates that there is an edge between vertex i and j. The following example explains the Adjacency matrix of a graph:
Graph Representation using Adjacency Matrix - The Coding Shala

Graph Representation using Adjacency Matrix Java Program

We have given the number of vertices 'v' and edges 'E' of a bidirectional graph. Our task is to build a graph through the adjacency matrix and print it.

Example 1:
Input:
5 7
0 1
0 4
1 2
1 3
1 4
2 3
3 4
Output:
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 

Java Code:

import java.util.*;

class GraphMatrix{
 int v;
 int[][] matrix;
 
 GraphMatrix(int v){
  this.v = v;
  matrix = new int[v][v];
 }
 
 void connect(int v1, int v2) {
  matrix[v1][v2] = 1;
  matrix[v2][v1] = 1; //bidirectional
 }
 
 void display() {
  System.out.println("Adjacency Matrix of Graph is: ");
  for(int i=0;i<v;i++) {
   for(int j=0; j<v; j++) {
    System.out.print(matrix[i][j]+" ");
   }
   System.out.println();
  }
 }
}

public class Main{
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int vertex = sc.nextInt();
  int edges = sc.nextInt();
  
  GraphMatrix gm = new GraphMatrix(vertex);
  
  //making matrix
  while(edges-->0) {
   int point1 = sc.nextInt();
   int point2 = sc.nextInt();
   
   gm.connect(point1, point2);
  }
  gm.display();
  sc.close();
 }
}



Other Posts You May Like
Prev<< Graph Representation Using Adjacency list                                                                             NEXT >>#
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala