-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDIGraph.java
100 lines (88 loc) · 2.14 KB
/
DIGraph.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.*;
/**
*
* @author TheDarkLord a.k.a Gaurav Shrivastava
*/
public class Graph {
public Map<Integer, Set<Integer>> edges = new TreeMap<Integer, Set<Integer>>();
/**
* Returns the number of vertices in this graph.
*
* @return the number of vertices in this graph
*/
private final int V = 0;
private int E = 0;
public int V() {
return V;
}
/**
* Returns the number of edges in this graph.
*
* @return the number of edges in this graph
*/
public int E() {
return E;
}
/**
* Adds the undirected edge v-w to this graph.
*
* @param v one vertex in the edge
* @param w the other vertex in the edge
* @throws IndexOutOfBoundsException unless both 0 <= v < V and 0 <= w < V
*/
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);
}
// private void validateVertex(int v) {
// if (v < 0 || v >= V)
// throw new IndexOutOfBoundsException("vertex " + v + " is not between 0 and " + (V-1));
// }
public Iterable<Integer> adj(int v) {
// validateVertex(v);
return edges.get(v);
}
/**
* Returns the degree of vertex <tt>v</tt>.
*
* @param v the vertex
* @return the degree of vertex <tt>v</tt>
* @throws IndexOutOfBoundsException unless 0 <= v < V
*/
public int degree(int v) {
// validateVertex(v);
return edges.get(v).size();
}
// Usage example
public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(0, 1);
g.addEdge(1, 2);
System.out.println(g.adj(1));
System.out.println(g.degree(0));
g.removeEdge(1, 0);
System.out.println(g.edges);
g.removeNode(1);
System.out.println(g.edges);
}
}