-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectedGraph.java
50 lines (42 loc) · 1.28 KB
/
DirectedGraph.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
// implemented as a weighted digraph, weights can
// be ignored, bi-directional edges can be added.
import Queue;
public class Graph {
private final int numVertices;
private EdgeNode[] edgeLists;
private class EdgeNode {
private int to;
private EdgeNode next;
public EdgeNode(int tu) {
to = tu;
}
}
public Graph(int verts) {
numVertices = verts;
edgeLists = new Node[numVertices];
for (int i = 0; i < numVertices; i++) {
edgeLists[i] = new Node();
}
}
public void addEdge(int from, int to) {
// see if edge is already present
for (EdgeNode curr = edgeLists[from]; curr != null; curr = curr.next) {
if (curr.to == to) { return; }
}
// add edge to beginning of list
EdgeNode node = new EdgeNode(to);
node.next = edgeLists[from];
edgeLists[from] = node;
}
public void addBiEdge(int from, int to) {
addEdge(from, to);
addEdge(to, from);
}
public Iterable<Integer> adjacent(int vert) {
Queue<Integer> q = new Queue<Integer>();
for (EdgeNode curr = edgeLists[vert]; curr != null; curr = curr.next) {
q.enqueue(curr.to);
}
return q;
}
}