Skip to content

Commit af383d7

Browse files
committed
Add adjacency matrix representation
1 parent 7b4d1f9 commit af383d7

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)