-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjListGraph.java
More file actions
42 lines (34 loc) · 1.05 KB
/
AdjListGraph.java
File metadata and controls
42 lines (34 loc) · 1.05 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
import java.util.HashSet;
import java.util.Set;
/**
* Created by Phil on 8/14/2015.
*/
public class AdjListGraph {
private int edges;
private int vertices;
private Set<Integer>[] adj;
public AdjListGraph(int numVertices) {
edges = 0;
vertices = numVertices;
adj = new Set[numVertices];
for(int i = 0; i < vertices; i++) {
adj[i] = new HashSet();
}
}
public void addEdge(int vertexIndexA, int vertexIndexB) {
if(!isValidVertex(vertexIndexA) || !isValidVertex(vertexIndexB)) return;
adj[vertexIndexA].add(vertexIndexB);
adj[vertexIndexB].add(vertexIndexA);
edges++;
}
private boolean isValidVertex(int vertexIndex) {
return vertexIndex >=0 && vertexIndex < vertices;
}
public Iterable<Integer> adj(int vertexIndex) {
if(!isValidVertex(vertexIndex)) throw new IndexOutOfBoundsException(vertexIndex + " not in the Graph!");
return(adj[vertexIndex]);
}
public int numVertices() {
return this.vertices;
}
}