File tree 1 file changed +39
-0
lines changed
src/main/java/com/packt/datastructuresandalg/lesson6/graph
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .packt .datastructuresandalg .lesson6 .graph ;
2
+
3
+ public class AdjacencyMatrixGraph {
4
+ int [][] adj ;
5
+
6
+ public AdjacencyMatrixGraph (int nodes ) {
7
+ this .adj = new int [nodes ][nodes ];
8
+ }
9
+
10
+ public void addEdge (int u , int v ) {
11
+ this .adj [u ][v ] = 1 ;
12
+ }
13
+
14
+ @ Override
15
+ public String toString () {
16
+ String res = "" ;
17
+ for (int i = 0 ; i < this .adj .length ; i ++) {
18
+ res += (i + ":" );
19
+ for (int j = 0 ; j < this .adj [i ].length ; j ++)
20
+ res += (" " + adj [i ][j ]);
21
+ if (i + 1 < adj .length )
22
+ res += "\n " ;
23
+ }
24
+ return res ;
25
+ }
26
+
27
+ public static void main (String [] args ) {
28
+ AdjacencyMatrixGraph g = new AdjacencyMatrixGraph (6 );
29
+ g .addEdge (0 , 1 );
30
+ g .addEdge (0 , 3 );
31
+ g .addEdge (1 , 4 );
32
+ g .addEdge (2 , 4 );
33
+ g .addEdge (2 , 5 );
34
+ g .addEdge (3 , 1 );
35
+ g .addEdge (4 , 3 );
36
+ g .addEdge (5 , 5 );
37
+ System .out .println (g );
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments