-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEdgeWeightedDigraph.java
More file actions
58 lines (50 loc) · 1.65 KB
/
Copy pathEdgeWeightedDigraph.java
File metadata and controls
58 lines (50 loc) · 1.65 KB
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
public class EdgeWeightedDigraph {
/* An implementation of the EdgeWeightedDigraph */
private final int V; // number of vertices
private int E; // number of edges
private final Bag<DirectedEdge>[] adj; // an array of bag (of edges)
/* Constructor */
public EdgeWeightedDigraph(int V) {
this.V = V;
// initialise graph array
this.adj = (Bag<DirectedEdge>[]) new Bag[V];
// initialise every bag
for (int i = 0; i < V; i++)
adj[i] = new Bag<DirectedEdge>();
}
/* API: Add an edge to the graph */
public void addEdge(DirectedEdge e) {
// get vertices to add edge between
int v = e.from();
adj[v].add(e);
E += 1;
}
/* API: Iterate through all edges adjacent to a vertex */
public Iterable<DirectedEdge> adj(int v) {
return adj[v];
}
/* API: Get number of vertices */
public int V() {
return this.V;
}
/* API: Get number of edges */
public int E() {
return this.E;
}
/* API: Get all edges in graph */
public Iterable<DirectedEdge> edges() {
// If repeat is true, count all edges twice as this is an undirected graph
Bag<DirectedEdge> edges = new Bag<DirectedEdge>();
for (int i = 0; i < this.V; i++)
for (DirectedEdge e : adj[i])
edges.add(e);
return edges;
}
/* Get a string representation of the graph */
public String toString() {
StringBuilder graph = new StringBuilder();
for (DirectedEdge e : edges())
graph.append(e.toString() + "\n");
return graph.toString();
}
}