Adjacency Matrix Java Implementation

 Adjacency Matrix Java Implementation :-


In This article i am going to Implement the Adjacency Matrix using Java. So if you don't Know anything about Adjacency Matrix Watch this video before going to Implementation :


 

I hope after watching this video you will have Good knowledge of Adjacency Matrix and now you are ready to implement this logic First try yourself if you are not able watch this video.

 

After Watching video you will be able to code for UnDirected Graph , so try for Directed Graph and weighted Graph also if you can then do comment in blog Comment section and also youtube video Comment Section. and if you are not able to code then comment i'll Update this blog.

Java Implementation of Adjacency Matrix for Undirected Graph :

import java.util.Scanner;

public class AdjacencyMatrix {

int vertices;

public int adjMat[][];

public AdjacencyMatrix(int vertices){

this.vertices = vertices;

adjMat = new int[vertices][vertices];

}

public void addEdges(int src,int dest) {

adjMat[src][dest] = 1;

adjMat[dest][src] = 1;

}

public void print() {

for(int[] arr:adjMat) {

for(int ele:arr) {

System.out.print(ele+" ");

}

System.out.println();

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner scan = new Scanner(System.in);

System.out.println("enter the number of vertices");

int v = scan.nextInt();

AdjacencyMatrix am = new AdjacencyMatrix(v);

System.out.println("enter the number of edges");

int e = scan.nextInt();

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

System.out.println("enter the source");

int src = scan.nextInt();

System.out.println("enter the destination");

int dest = scan.nextInt();

am.addEdges(src, dest);

}

am.print();

}


}



Post a Comment

0 Comments