Skip to content

Commit 4266b75

Browse files
committed
Added Graph.java
1 parent c00159e commit 4266b75

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Graph.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
2+
public class Graph {
3+
private int[][] edges; // matrix
4+
private int nV; // number of vertices
5+
private int nE; // number of edges
6+
7+
// constructor with n vertices
8+
public Graph(int nV) {
9+
this.nV = nV;
10+
this.nE = 0;
11+
edges = new int[nV][nV]; // initialize matrix with 0
12+
}
13+
14+
// method to check if a vertex is valid
15+
private boolean validV(int v) {
16+
return (v >= 0 && v < nV);
17+
}
18+
19+
// method to insert edge
20+
public void insertEdge(int v, int w) {
21+
if (validV(v) && validV(w) && edges[v][w] == 0) {
22+
edges[v][w] = 1;
23+
edges[w][v] = 1; // undirected graph
24+
nE++;
25+
}
26+
}
27+
28+
// method to remove edge
29+
public void removeEdge(int v, int w) {
30+
if (validV(v) && validV(w) && edges[v][w] == 1) {
31+
edges[v][w] = 0;
32+
edges[w][v] = 0;
33+
nE--;
34+
}
35+
}
36+
37+
// method to check if two vertices are adjacent
38+
public boolean adjacent(int v, int w) {
39+
return validV(v) && validV(w) && edges[v][w] != 0;
40+
}
41+
42+
// method to display graph
43+
public void showGraph() {
44+
System.out.println("Number of vertices: " + nV);
45+
System.out.println("Number of edges: " + nE);
46+
for (int i = 0; i < nV; i++) {
47+
for (int j = i + 1; j < nV; j++) {
48+
if (edges[i][j] == 1) {
49+
System.out.println("Edges " + i + " - " + j);
50+
}
51+
}
52+
}
53+
}
54+
55+
public int getNumVertices() {
56+
return nV;
57+
}
58+
}

0 commit comments

Comments
 (0)