-
Notifications
You must be signed in to change notification settings - Fork 1
/
Graph.java
46 lines (40 loc) · 866 Bytes
/
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
package Graphs;
import java.util.*;
public class Graph {
public Map<Integer, Set<Integer>> edges = new TreeMap<>();
public void addNode(int u) {
if (!edges.containsKey(u)) {
edges.put(u, new TreeSet<Integer>());
}
}
public void removeNode(int u) {
if (!edges.containsKey(u)) {
return;
}
for (int v : edges.get(u)) {
edges.get(v).remove(u);
}
edges.remove(u);
}
public void addEdge(int u, int v) {
addNode(u);
addNode(v);
edges.get(u).add(v);
edges.get(v).add(u);
}
public void removeEdge(int u, int v) {
edges.get(u).remove(v);
edges.get(v).remove(u);
}
// Usage example
public static void main(String[] args) {
Graph g = new Graph();
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);
}
}