-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEdgeWeightedGraph.java
More file actions
65 lines (57 loc) · 1.89 KB
/
Copy pathEdgeWeightedGraph.java
File metadata and controls
65 lines (57 loc) · 1.89 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
59
60
61
62
63
64
65
public class EdgeWeightedGraph {
/* An implementation of the EdgeWeightedGraph */
private final int V; // number of vertices
private int E; // number of edges
private final Bag<Edge>[] adj; // an array of bag (of edges)
/* Constructor */
public EdgeWeightedGraph(int V) {
this.V = V;
// initialise graph array
this.adj = (Bag<Edge>[]) new Bag[V];
// initialise every bag
for (int i = 0; i < V; i++)
adj[i] = new Bag<Edge>();
}
/* API: Add an edge to the graph */
public void addEdge(Edge e) {
// get vertices to add edge between
int v = e.either(), w = e.other(v);
adj[v].add(e);
adj[w].add(e);
E += 1;
}
/* API: Iterate through all edges adjacent to a vertex */
public Iterable<Edge> 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<Edge> edges(boolean repeat) {
// If repeat is true, count all edges twice as this is an undirected graph
Bag<Edge> edges = new Bag<Edge>();
for (int i = 0; i < this.V; i++)
for (Edge e : adj[i])
if (repeat) edges.add(e);
else {
// get other vertex
int other = e.other(i);
// ignore this edge if other < i as this edge is already added there
if (other > i) edges.add(e);
}
return edges;
}
/* Get a string representation of the graph */
public String toString() {
StringBuilder graph = new StringBuilder();
for (Edge e : edges(true))
graph.append(e.toString() + "\n");
return graph.toString();
}
}