-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java
85 lines (69 loc) · 2.11 KB
/
Graph.java
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cs146s20.larson.project03;
import java.util.*;
public class Graph<T> {
private Map<T, List<T>> adjacencyList;
public Graph() {
adjacencyList = new HashMap<>();
}
public void addVertex(T vertex) {
adjacencyList.put(vertex, new LinkedList<T>());
}
public void addEdge(T source, T destination, boolean bidirectional) {
if(!this.containsVertex(source)) {
addVertex(source);
}
if(!this.containsVertex(destination)) {
addVertex(destination);
}
adjacencyList.get(source).add(destination);
if(bidirectional) {
adjacencyList.get(destination).add(source);
}
}
/**
* The number of vertices in the graph
* @return integer representing the number of vertices
*/
public int order() {
return adjacencyList.keySet().size();
}
/**
* The number of edges in the graph
* @param bidirectional undirected graph
* @return integer representing the number of edges
*/
public int size(boolean bidirectional) {
int count = 0;
for (T vertex : adjacencyList.keySet()) {
count += adjacencyList.get(vertex).size();
}
if (bidirectional) {
count /= 2;
}
return count;
}
public boolean isEmpty() {
return adjacencyList.isEmpty();
}
public boolean containsVertex(T vertex) {
return adjacencyList.containsKey(vertex);
}
public boolean containsEdge(T source, T destination) {
return adjacencyList.get(source).contains(destination);
}
public void clear() {
adjacencyList.clear();
}
@Override
public String toString() {
String result = "";
for (T vertex : adjacencyList.keySet()) {
result += (vertex.toString() + ": ");
for (T edge : adjacencyList.get(vertex)) {
result += (edge.toString() + " ");
}
result += ("\n");
}
return result;
}
}