-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAdjacencyList.java
83 lines (63 loc) · 1.65 KB
/
AdjacencyList.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
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class AdjacencyList {
private Map<Integer, HashSet<Integer>> in; //in-neighbours
private Map<Integer, HashSet<Integer>> out; //out-neighbours
public AdjacencyList(int n) {
this.in = new HashMap<>();
this.out = new HashMap<>();
for(int v = 0; v < n; v++) {
this.in.put(v, null);
this.out.put(v, null);
}
}
public void addEdge(int orig, int dest) {
HashSet<Integer> inSet = this.in.get(dest);
if(inSet == null) {
inSet = new HashSet<>();
this.in.put(dest, inSet);
}
inSet.add(orig);
//updates out-neighbours
HashSet<Integer> outSet = this.out.get(orig);
if(outSet == null) {
outSet = new HashSet<>();
this.out.put(orig, outSet);
}
outSet.add(dest);
}
public void showVertices() {
for(int v = 0; v < this.in.size(); v++) {
System.out.println(v);
}
}
public void showEdges() {
for(int v = 0; v < this.out.size(); v++) {
HashSet<Integer> outSet = this.out.get(v);
if(outSet != null) {
for(int elem : this.out.get(v))
System.out.println(v + " -> " + elem);
System.out.println();
}
}
}
public int getNumVertices() {
return this.in.size();
}
public Set<Integer> getVerticesId() {
HashSet<Integer> vertices = new HashSet<>(this.out.keySet());
vertices.addAll(this.in.keySet());
return vertices;
}
public HashSet<Integer> getInEdges(int v) {
return this.in.get(v);
}
public HashSet<Integer> getOutEdges(int v) {
return this.out.get(v);
}
public boolean removeOutEdge(int source, int destination) {
return this.out.get(source).remove(destination);
}
}