-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedGraph.java
More file actions
437 lines (355 loc) · 11.4 KB
/
DirectedGraph.java
File metadata and controls
437 lines (355 loc) · 11.4 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
* Xi Wu - 22C
*/
package socialnetwork;
import java.util.Iterator;
import Graph.DictionaryInterface;
import Graph.GraphInterface;
import Graph.HeapPriorityQueue;
import Graph.LinkedDictionary;
import Graph.LinkedQueue;
import Graph.LinkedStack;
import Graph.PriorityQueueInterface;
import Graph.StackInterface;
public class DirectedGraph<T> implements GraphInterface<T>
{
private DictionaryInterface<T, VertexInterface<T>> vertices;
private int edgeCount;
public DirectedGraph()
{
vertices = new LinkedDictionary<>();
edgeCount = 0;
} // end default constructor
protected void resetVertices()
{
Iterator<VertexInterface<T>> vertexIterator = vertices.getValueIterator();
while (vertexIterator.hasNext())
{
VertexInterface<T> nextVertex = vertexIterator.next();
nextVertex.unvisit();
nextVertex.setCost(0);
nextVertex.setPredecessor(null);
} // end while
} // end resetVertices
public QueueInterface<T> getDepthFirstTraversal(T origin)
{
// Assumes graph is not empty
resetVertices();
QueueInterface<T> traversalOrder = new LinkedQueue<T>();
StackInterface<VertexInterface<T>> vertexStack = new LinkedStack<>();
VertexInterface<T> originVertex = vertices.getValue(origin);
originVertex.visit();
traversalOrder.enqueue(origin); // Enqueue vertex label
vertexStack.push(originVertex); // Enqueue vertex
while (!vertexStack.isEmpty())
{
VertexInterface<T> topVertex = vertexStack.peek();
VertexInterface<T> nextNeighbor = topVertex.getUnvisitedNeighbor();
if (nextNeighbor != null)
{
nextNeighbor.visit();
traversalOrder.enqueue(nextNeighbor.getLabel());
vertexStack.push(nextNeighbor);
}
else // All neighbors are visited
vertexStack.pop();
} // end while
return traversalOrder;
} // end getDepthFirstTraversal
public StackInterface<T> getTopologicalOrder()
{
resetVertices();
StackInterface<T> vertexStack = new LinkedStack<>();
int numberOfVertices = getNumberOfVertices();
for (int counter = 1; counter <= numberOfVertices; counter++)
{
VertexInterface<T> nextVertex = findTerminal();
nextVertex.visit();
vertexStack.push(nextVertex.getLabel());
} // end for
return vertexStack;
} // end getTopologicalOrder
/** Precondition: path is an empty stack (NOT null) */
public int getShortestPath(T begin, T end, StackInterface<T> path)
{
resetVertices();
boolean done = false;
QueueInterface<VertexInterface<T>> vertexQueue = new LinkedQueue<>();
VertexInterface<T> originVertex = vertices.getValue(begin);
VertexInterface<T> endVertex = vertices.getValue(end);
originVertex.visit();
// Assertion: resetVertices() has executed setCost(0)
// and setPredecessor(null) for originVertex
vertexQueue.enqueue(originVertex);
while (!done && !vertexQueue.isEmpty())
{
VertexInterface<T> frontVertex = vertexQueue.dequeue();
Iterator<VertexInterface<T>> neighbors =
frontVertex.getNeighborIterator();
while (!done && neighbors.hasNext())
{
VertexInterface<T> nextNeighbor = neighbors.next();
if (!nextNeighbor.isVisited())
{
nextNeighbor.visit();
nextNeighbor.setCost(1 + frontVertex.getCost());
nextNeighbor.setPredecessor(frontVertex);
vertexQueue.enqueue(nextNeighbor);
} // end if
if (nextNeighbor.equals(endVertex))
done = true;
} // end while
} // end while
// Traversal ends; construct shortest path
int pathLength = (int)endVertex.getCost();
path.push(endVertex.getLabel());
VertexInterface<T> vertex = endVertex;
while (vertex.hasPredecessor())
{
vertex = vertex.getPredecessor();
path.push(vertex.getLabel());
} // end while
return pathLength;
} // end getShortestPath
/** Precondition: path is an empty stack (NOT null) */
public double getCheapestPath(T begin, T end, StackInterface<T> path)
{
resetVertices();
boolean done = false;
// Use EntryPQ instead of Vertex because multiple entries contain
// the same vertex but different costs - cost of path to vertex is EntryPQ's priority value
PriorityQueueInterface<EntryPQ> priorityQueue = new HeapPriorityQueue<>();
VertexInterface<T> originVertex = vertices.getValue(begin);
VertexInterface<T> endVertex = vertices.getValue(end);
priorityQueue.add(new EntryPQ(originVertex, 0, null));
while (!done && !priorityQueue.isEmpty())
{
EntryPQ frontEntry = priorityQueue.remove();
VertexInterface<T> frontVertex = frontEntry.getVertex();
if (!frontVertex.isVisited())
{
frontVertex.visit();
frontVertex.setCost(frontEntry.getCost());
frontVertex.setPredecessor(frontEntry.getPredecessor());
if (frontVertex.equals(endVertex))
done = true;
else
{
Iterator<VertexInterface<T>> neighbors = frontVertex.getNeighborIterator();
Iterator<Double> edgeWeights = frontVertex.getWeightIterator();
while (neighbors.hasNext())
{
VertexInterface<T> nextNeighbor = neighbors.next();
Double weightOfEdgeToNeighbor = edgeWeights.next();
if (!nextNeighbor.isVisited())
{
double nextCost = weightOfEdgeToNeighbor + frontVertex.getCost();
priorityQueue.add(new EntryPQ(nextNeighbor, nextCost, frontVertex));
} // end if
} // end while
} // end if
} // end if
} // end while
// Traversal ends, construct cheapest path
double pathCost = endVertex.getCost();
path.push(endVertex.getLabel());
VertexInterface<T> vertex = endVertex;
while (vertex.hasPredecessor())
{
vertex = vertex.getPredecessor();
path.push(vertex.getLabel());
} // end while
return pathCost;
} // end getCheapestPath
protected VertexInterface<T> findTerminal()
{
boolean found = false;
VertexInterface<T> result = null;
Iterator<VertexInterface<T>> vertexIterator = vertices.getValueIterator();
while (!found && vertexIterator.hasNext())
{
VertexInterface<T> nextVertex = vertexIterator.next();
// If nextVertex is unvisited AND has only visited neighbors)
if (!nextVertex.isVisited())
{
if (nextVertex.getUnvisitedNeighbor() == null )
{
found = true;
result = nextVertex;
} // end if
} // end if
} // end while
return result;
} // end findTerminal
// Used for testing
public void displayEdges()
{
// System.out.println("\nEdges exist from the first vertex in each line to the other vertices in the line.");
// System.out.println("(Edge weights are given; weights are zero for unweighted graphs):\n");
Iterator<VertexInterface<T>> vertexIterator = vertices.getValueIterator();
while (vertexIterator.hasNext())
{
((Vertex<T>)(vertexIterator.next())).display();
} // end while
} // end displayEdges
private class EntryPQ implements Comparable<EntryPQ>
{
private VertexInterface<T> vertex;
private VertexInterface<T> previousVertex;
private double cost; // cost to nextVertex
private EntryPQ(VertexInterface<T> vertex, double cost, VertexInterface<T> previousVertex)
{
this.vertex = vertex;
this.previousVertex = previousVertex;
this.cost = cost;
} // end constructor
public VertexInterface<T> getVertex()
{
return vertex;
} // end getVertex
public VertexInterface<T> getPredecessor()
{
return previousVertex;
} // end getPredecessor
public double getCost()
{
return cost;
} // end getCost
public int compareTo(EntryPQ otherEntry)
{
// Using opposite of reality since our priority queue uses a maxHeap;
// could revise using a minheap
return (int)Math.signum(otherEntry.cost - cost);
} // end compareTo
public String toString()
{
return vertex.toString() + " " + cost;
} // end toString
} // end EntryPQ
@Override
public boolean addVertex(T vertexLabel) {
VertexInterface<T> addOutcome =
vertices.add(vertexLabel, new Vertex<>(vertexLabel));
return addOutcome == null;
}
@Override
public boolean addEdge(T begin, T end, double edgeWeight) {
boolean result = false;
VertexInterface<T> beginVertex = vertices.getValue(begin);
VertexInterface<T> endVertex = vertices.getValue(end);
if ((beginVertex != null) && (endVertex != null))
result = beginVertex.connect(endVertex, edgeWeight);
if (result)
edgeCount++;
return result;
}
/** Adds an unweighted edge between two given distinct vertices
that are currently in this graph. The desired edge must not
already be in the graph. In a directed graph, the edge points
toward the second vertex given.*/
@Override
public boolean addEdge(T begin, T end) {
return addEdge(begin, end, 0);
}
@Override
public boolean hasEdge(T begin, T end) {
boolean found = false;
VertexInterface<T> beginVertex = vertices.getValue(begin);
VertexInterface<T> endVertex = vertices.getValue(end);
if ((beginVertex != null) && (endVertex != null)) {
Iterator<VertexInterface<T>> neighbors =
beginVertex.getNeighborIterator();
while (!found && neighbors.hasNext()) {
VertexInterface<T> nextNeighbor = neighbors.next();
if(endVertex.equals(nextNeighbor))
found = true;
}
}
return found;
}
@Override
public boolean isEmpty() {
return vertices.isEmpty();
}
@Override
public int getNumberOfVertices() {
return vertices.getSize();
}
@Override
public int getNumberOfEdges() {
return edgeCount;
}
@Override
public void clear() {
vertices.clear();
edgeCount = 0;
}
@Override
public QueueInterface<T> getBreadthFirstTraversal(T origin) {
resetVertices();
QueueInterface<T> traversalOrder = new LinkedQueue<>();
QueueInterface<VertexInterface<T>> vertexQueue = new LinkedQueue<>();
VertexInterface<T> originVertex = vertices.getValue(origin);
originVertex.visit();
traversalOrder.enqueue(origin);
vertexQueue.enqueue(originVertex);
while(!vertexQueue.isEmpty()) {
VertexInterface<T> frontVertex = vertexQueue.dequeue();
Iterator<VertexInterface<T>> neighbors =
frontVertex.getNeighborIterator();
while(neighbors.hasNext()) {
VertexInterface<T> nextNeighbor = neighbors.next();
if (!nextNeighbor.isVisited()) {
nextNeighbor.visit();
traversalOrder.enqueue(nextNeighbor.getLabel());
vertexQueue.enqueue(nextNeighbor);
}
}
}
return traversalOrder;
}
/** Sees whether a vertex exists in the graph.*/
public boolean hasVertex(T vertexLabel){
Iterator<VertexInterface<T>> vertex = vertices.getValueIterator();
T label = null;
boolean result = false;
//remove related edge in other vertex.
while (vertex.hasNext()){
label = vertex.next().getLabel();
if (label.equals(vertexLabel)){
result = true;
}
}
return result;
}
public Iterator<T> getVerticesKeyIterator() {
return vertices.getKeyIterator();
}
public boolean removeEdge(T begin, T end) {
boolean result = false;
VertexInterface<T> first = getVertex(begin);
VertexInterface<T> second = getVertex(end);
result = first.disconnect(second);
return result;
}
public VertexInterface<T> getVertex(T key){
return vertices.getValue(key);
}
// Remove a given vertex to this graph
public boolean removeVertex(T vertexLabel) {
Iterator<VertexInterface<T>> neighbors =
vertices.getValue(vertexLabel).getNeighborIterator();
T nextVertex = null;
boolean result = false;
if (hasVertex(vertexLabel)) {
result = true;
// remove related edge in other vertex
while (neighbors.hasNext()) {
nextVertex = neighbors.next().getLabel();
removeEdge(vertexLabel, nextVertex);
}
vertices.remove(vertexLabel);
}
return result;
}
} // end DirectedGraph