Advertisement
a_pramanik

Adjacency Matrix in JAVA

Mar 30th, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. public class AdjacencyMatrix {
  2.  
  3.  
  4.     public static int[][] matrix = new int[20][20];
  5.    
  6.     public static void addEdge(int src, int dst)
  7.     {
  8.         matrix[src][dst]=1;
  9.         matrix[dst][src]=1;
  10.     }
  11.    
  12.     public static void printMatrix(int vertices)
  13.     {
  14.         for(int i=1; i<=vertices; i++){
  15.             for(int j=1; j<=vertices; j++){
  16.                 System.out.print(matrix[i][j]+" ");
  17.             }
  18.             System.out.println();
  19.         }
  20.     }
  21.    
  22.    
  23.     public static void main(String[] args) {
  24.         // TODO code application logic here
  25.         Scanner sc = new Scanner(System.in);
  26.         int vertices, edges;
  27.        
  28.         System.out.println("Enter number of vertices: ");
  29.         vertices = sc.nextInt();
  30.         System.out.println("Enter number of edges: ");
  31.         edges = sc.nextInt();
  32.         int src, dst;
  33.         for(int i=1; i<=edges; i++){
  34.             System.out.println("Enter the source node: ");
  35.             src = sc.nextInt();
  36.             System.out.println("Enter the destination node: ");
  37.             dst = sc.nextInt();
  38.             addEdge(src, dst);
  39.         }
  40.        
  41.         printMatrix(vertices);
  42.        
  43.     }
  44.    
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement