-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
350 lines (317 loc) · 10.6 KB
/
Graph.java
File metadata and controls
350 lines (317 loc) · 10.6 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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* file name: Graph.java
* author: Jack Dai
* last modified: 11/20/2025
* purpose of the class:
* This class builds the Graph structure that contains Vertex and Edge objects.
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.PriorityQueue;
public class Graph {
private ArrayList<Vertex> vertices;
private ArrayList<Edge> edges;
/**
* this constructor is equivalent to Graph(0).
*/
public Graph() {
this(0);
}
/**
* this constructor is equivalent to Graph(n, 0.0).
*
* @param n
*/
public Graph(int n) {
this(n, 0.0);
}
/**
* The default constructor creates a graph of n vertices where each pair of
* vertices has an edge
* between them of distance 1 with probability given by the supplied
* probability.
*
* @param n
* @param probability
*/
public Graph(int n, double probability) {
// Initialize vertex and edge lists
vertices = new ArrayList<Vertex>();
edges = new ArrayList<Edge>();
for (int i = 0; i < n; i++)
vertices.add(new Vertex());
// For each unordered pair, add an edge with given probability
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (Math.random() <= probability) {
Edge e = new Edge(vertices.get(i), vertices.get(j), 1.0);
edges.add(e);
vertices.get(i).addEdge(e);
vertices.get(j).addEdge(e);
}
}
}
}
/**
* A graph constructor that takes in a filename and builds
* the graph with the number of vertices and specific edges
* specified.
*
* @param filename
*/
public Graph(String filename) {
try {
// Setup for reading the file
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
// Get the number of vertices from the file and initialize that number of
// vertices
vertices = new ArrayList<Vertex>();
Integer numVertices = Integer.valueOf(br.readLine().split(": ")[1]);
for (int i = 0; i < numVertices; i++) {
vertices.add(new Vertex());
}
// Read in the edges specified by the file and create them
edges = new ArrayList<Edge>(); // If you used a different data structure to store Edges, you'll need to
// update
// this line
String header = br.readLine(); // We don't use the header, but have to read it to skip to the next line
// Read in all the lines corresponding to edges
String line = br.readLine();
while (line != null) {
// Parse out the index of the start and end vertices of the edge
String[] arr = line.split(",");
Integer start = Integer.valueOf(arr[0]);
Integer end = Integer.valueOf(arr[1]);
// Make the edge that starts at start and ends at end with weight 1
Edge edge = new Edge(vertices.get(start), vertices.get(end), 1.);
// Add the edge to the set of edges for each of the vertices
vertices.get(start).addEdge(edge);
vertices.get(end).addEdge(edge);
// Add the edge to the ArrayList of edges in the graph
this.edges.add(edge);
// Read the next line
line = br.readLine();
}
// call the close method of the BufferedReader:
br.close();
} catch (FileNotFoundException ex) {
System.out.println("Graph constructor:: unable to open file " + filename + ": file not found");
} catch (IOException ex) {
System.out.println("Graph constructor:: error reading file " + filename);
}
}
/**
* This method returns the number of vertices
*
* @return the number of vertices
*/
public int size() {
if (this.vertices == null) {
return 0;
}
return this.vertices.size();
}
/**
* This method returns an ArrayList object that can be used to iterate over the
* vertices (don't re-invent the wheel here, this should be as simple as
* returning the structure you're using to keep track of the vertices)
*
* @return an ArrayList object that can be used to iterate over the vertices
*/
public ArrayList<Vertex> getVertices() {
return this.vertices;
}
/**
* This method returns an ArrayList object that iterates over the edges.
*
* @return an ArrayList object that iterates over the edges.
*/
public ArrayList<Edge> getEdges() {
return this.edges;
}
/**
* This method creates a new Vertex, adds it to the Graph, and returns it.
*
* @return the new added Vertex
*/
public Vertex addVertex() {
if (this.vertices == null) {
this.vertices = new ArrayList<Vertex>();
}
Vertex v = new Vertex();
this.vertices.add(v);
return v;
}
/**
* This method creates a new Edge, adds it to the Graph (make sure the endpoints
* are aware of this new Edge), and returns it.
*
* @param u
* @param v
* @param distance
* @return the new added Edge
*/
public Edge addEdge(Vertex u, Vertex v, double distance) {
if (u == null || v == null) {
return null;
}
if (this.edges == null) {
this.edges = new ArrayList<Edge>();
}
Edge e = new Edge(u, v, distance);
this.edges.add(e);
u.addEdge(e);
v.addEdge(e);
return e;
}
/**
* This method returns the Edge between u and v if such an Edge exists,
* otherwise returns null.
*
* @param u
* @param v
* @return the Edge between u and v if such an Edge exists, otherwise returns
* null.
*/
public Edge getEdge(Vertex u, Vertex v) {
if (u == null || v == null) {
return null;
}
// search incident edges of u for an edge connecting to v
for (Edge e : u.incidentEdges()) {
Vertex other = e.other(u);
if (other == v) {
return e;
}
}
return null;
}
/**
* This method returns the Vertex at index
*
* @param index
* @return the Vertex at index
*/
public Vertex getVertex(int index) {
if (this.vertices == null) {
return null;
}
return this.vertices.get(index);
}
/**
* If the given Vertex vertex is in this Graph, removes it and returns true.
* Otherwise, returns false.
*
* @param vertex
* @return true if the given Vertex vertex is in this Graph. Otherwise, returns
* false.
*/
public boolean remove(Vertex vertex) {
if (vertex == null || this.vertices == null) {
return false;
}
if (!this.vertices.contains(vertex)) {
return false;
}
// Remove all incident edges first
ArrayList<Edge> incident = new ArrayList<Edge>(vertex.incidentEdges());
for (Edge e : incident) {
this.remove(e);
}
// Remove the vertex from the list
return this.vertices.remove(vertex);
}
/**
* If the given Edge is in the Graph, removes it and returns true. Otherwise,
* returns false.
*
* @param edge
* @return true if the given Edge is in the Graph. Otherwise,
* returns false.
*/
public boolean remove(Edge edge) {
if (edge == null || this.edges == null) {
return false;
}
boolean removed = this.edges.remove(edge);
if (!removed) {
return false;
}
// inform endpoints to remove this edge
try {
Vertex[] verts = edge.vertices();
if (verts != null) {
for (Vertex v : verts) {
if (v != null) {
v.removeEdge(edge);
}
}
}
} catch (Exception ex) {
// ignore
}
return true;
}
/**
* This method uses Dijkstra's algorithm to compute the minimal distance in this
* Graph from the given Vertex source to all other Vertices in the graph. The
* HashMap returned maps each Vertex to its distance from the source.
*
* @param source
* @return maps each Vertex to its distance from the source.
*/
public HashMap<Vertex, Double> distanceFrom(Vertex source) {
HashMap<Vertex, Double> dist = new HashMap<Vertex, Double>();
if (this.vertices == null) {
return dist;
}
// Initialize distances
for (Vertex v : this.vertices) {
dist.put(v, Double.POSITIVE_INFINITY);
}
if (source == null || !dist.containsKey(source)) {
return dist;
}
dist.put(source, 0.0);
// Priority queue ordered by current distance in dist map
PriorityQueue<Vertex> pq = new PriorityQueue<Vertex>(new java.util.Comparator<Vertex>() {
public int compare(Vertex a, Vertex b) {
double da = dist.get(a);
double db = dist.get(b);
return Double.compare(da, db);
}
});
// add all vertices
for (Vertex v : this.vertices) {
pq.add(v);
}
while (!pq.isEmpty()) {
Vertex u = pq.poll();
double du = dist.get(u);
if (du == Double.POSITIVE_INFINITY) {
break; // remaining vertices unreachable
}
for (Edge e : u.incidentEdges()) {
Vertex v = e.other(u);
if (v == null) {
continue;
}
double alt = du + e.distance();
double dv = dist.get(v);
if (alt < dv) {
// decrease priority: remove and re-add with new distance
dist.put(v, alt);
// Java PQ doesn't support decrease-key; remove and re-add
pq.remove(v);
pq.add(v);
}
}
}
return dist;
}
}