-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathAdjacencyMatrixGraph.java
More file actions
51 lines (39 loc) · 1.13 KB
/
Copy pathAdjacencyMatrixGraph.java
File metadata and controls
51 lines (39 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package util;
public class AdjacencyMatrixGraph {
private int adjMatrix[][];
private int numVertices;
// Initialize the matrix
public AdjacencyMatrixGraph(int numVertices) {
this.numVertices = numVertices;
adjMatrix = new int[numVertices][numVertices];
}
// Add edges
public void addEdge(int i, int j) {
adjMatrix[i][j] = 1;
adjMatrix[j][i] = 1;
}
// Remove edges
public void removeEdge(int i, int j) {
adjMatrix[i][j] = 0;
adjMatrix[j][i] = 0;
}
// Add a new vertex
public void addVertex() {
int[][] newAdjMatrix = new int[numVertices + 1][numVertices + 1];
for (int i = 0; i < numVertices; i++)
for (int j = 0; j < numVertices; j++)
newAdjMatrix[i][j] = adjMatrix[i][j];
adjMatrix = newAdjMatrix;
numVertices++;
}
// Remove a vertex
public void removeVertex(int v) {
int[][] newAdjMatrix = new int[numVertices - 1][numVertices - 1];
for (int i = 0; i < numVertices; i++)
for (int j = 0; j < numVertices; j++)
if (i != v && j != v)
newAdjMatrix[i][j] = adjMatrix[i][j];
adjMatrix = newAdjMatrix;
numVertices--;
}
}