- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGraph.java
More file actions
Latest commit
46 lines (40 loc) · 866 Bytes
/
Copy pathGraph.java
File metadata and controls
46 lines (40 loc) · 866 Bytes
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
packageGraphs;
importjava.util.*;
publicclassGraph {
publicMap<Integer, Set<Integer>> edges = newTreeMap<>();
publicvoidaddNode(intu) {
if (!edges.containsKey(u)) {
edges.put(u, newTreeSet<Integer>());
}
}
publicvoidremoveNode(intu) {
if (!edges.containsKey(u)) {
return;
}
for (intv : edges.get(u)) {
edges.get(v).remove(u);
}
edges.remove(u);
}
publicvoidaddEdge(intu, intv) {
addNode(u);
addNode(v);
edges.get(u).add(v);
edges.get(v).add(u);
}
publicvoidremoveEdge(intu, intv) {
edges.get(u).remove(v);
edges.get(v).remove(u);
}
// Usage example
publicstaticvoidmain(String[] args) {
Graphg = newGraph();
g.addEdge(0, 1);
g.addEdge(1, 2);
System.out.println(g.edges);
g.removeEdge(1, 0);
System.out.println(g.edges);
g.removeNode(1);
System.out.println(g.edges);
}
}