-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphList.java
More file actions
100 lines (81 loc) · 2.51 KB
/
GraphList.java
File metadata and controls
100 lines (81 loc) · 2.51 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;
public class GraphList<T extends Comparable<T>> {
// Attributes
public Map<T, List<T>> adjList = new HashMap<>();
private boolean isDirected;
// Constructors
public GraphList(boolean isDirected) {
this.isDirected = isDirected;
}
// Methods
public void addVertex(T vertex) {
adjList.put(vertex, new LinkedList<>());
}
public void addEdge(T source, T destination) {
if (!adjList.containsKey(source)) {
addVertex(source);
}
if (!adjList.containsKey(destination)) {
addVertex(destination);
}
if (!adjList.get(source).contains(destination)) {
adjList.get(source).add(destination);
if (!isDirected) {
adjList.get(destination).add(source);
}
}
}
public void removeVertex(T vertex) {
adjList.values().forEach(e -> e.remove(vertex));
adjList.remove(vertex);
}
public int getVertexCount() {
return adjList.keySet().size();
}
public int getEdgeCount() {
int count = 0;
for (T vertex : adjList.keySet()) {
count += adjList.get(vertex).size();
}
if (!isDirected) {
count /= 2;
}
return count;
}
public boolean hasVertex(T vertex) {
return adjList.containsKey(vertex);
}
public boolean hasEdge(T source, T destination) {
return adjList.containsKey(source) && adjList.get(source).contains(destination);
}
public List<T> getNeighbors(T vertex) {
return adjList.get(vertex);
}
// Methods - Traversal
public List<T> breadthFirstSearch(T start) {
List<T> result = new LinkedList<>();
LinkedList<T> queue = new LinkedList<>();
Map<T, Boolean> visited = new HashMap<>();
queue.add(start);
visited.put(start, true);
while (!queue.isEmpty()) {
T vertex = queue.poll();
result.add(vertex);
for (T neighbor : getNeighbors(vertex)) {
if (visited.get(neighbor) == null || !visited.get(neighbor)) {
queue.add(neighbor);
visited.put(neighbor, true);
}
}
}
return result;
}
@Override
public String toString() {
T start = adjList.keySet().iterator().next();
return breadthFirstSearch(start).toString();
}
}