forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.java
581 lines (476 loc) · 15.8 KB
/
Graph.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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package com.jwetherell.algorithms.data_structures;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Graph. Could be directed or undirected depending on the TYPE enum. A graph is
* an abstract representation of a set of objects where some pairs of the
* objects are connected by links.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Graph_(mathematics)">Graph (Wikipedia)</a>
* <br>
* @author Justin Wetherell <[email protected]>
*/
@SuppressWarnings("unchecked")
public class Graph<T extends Comparable<T>> {
private List<Vertex<T>> allVertices = new ArrayList<Vertex<T>>();
private List<Edge<T>> allEdges = new ArrayList<Edge<T>>();
public enum TYPE {
DIRECTED, UNDIRECTED
}
/** Defaulted to undirected */
private TYPE type = TYPE.UNDIRECTED;
public Graph() { }
public Graph(TYPE type) {
this.type = type;
}
/** Deep copies **/
public Graph(Graph<T> g) {
type = g.getType();
// Copy the vertices which also copies the edges
for (Vertex<T> v : g.getVertices())
this.allVertices.add(new Vertex<T>(v));
for (Vertex<T> v : this.getVertices()) {
for (Edge<T> e : v.getEdges()) {
this.allEdges.add(e);
}
}
}
/**
* Creates a Graph from the vertices and edges. This defaults to an undirected Graph
*
* NOTE: Duplicate vertices and edges ARE allowed.
* NOTE: Copies the vertex and edge objects but does NOT store the Collection parameters itself.
*
* @param vertices Collection of vertices
* @param edges Collection of edges
*/
public Graph(Collection<Vertex<T>> vertices, Collection<Edge<T>> edges) {
this(TYPE.UNDIRECTED, vertices, edges);
}
/**
* Creates a Graph from the vertices and edges.
*
* NOTE: Duplicate vertices and edges ARE allowed.
* NOTE: Copies the vertex and edge objects but does NOT store the Collection parameters itself.
*
* @param vertices Collection of vertices
* @param edges Collection of edges
*/
public Graph(TYPE type, Collection<Vertex<T>> vertices, Collection<Edge<T>> edges) {
this(type);
this.allVertices.addAll(vertices);
this.allEdges.addAll(edges);
for (Edge<T> e : edges) {
final Vertex<T> from = e.from;
final Vertex<T> to = e.to;
if (!this.allVertices.contains(from) || !this.allVertices.contains(to))
continue;
from.addEdge(e);
if (this.type == TYPE.UNDIRECTED) {
Edge<T> reciprical = new Edge<T>(e.cost, to, from);
to.addEdge(reciprical);
this.allEdges.add(reciprical);
}
}
}
public TYPE getType() {
return type;
}
public List<Vertex<T>> getVertices() {
return allVertices;
}
public List<Edge<T>> getEdges() {
return allEdges;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int code = this.type.hashCode() + this.allVertices.size() + this.allEdges.size();
for (Vertex<T> v : allVertices)
code *= v.hashCode();
for (Edge<T> e : allEdges)
code *= e.hashCode();
return 31 * code;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object g1) {
if (!(g1 instanceof Graph))
return false;
final Graph<T> g = (Graph<T>) g1;
final boolean typeEquals = this.type == g.type;
if (!typeEquals)
return false;
final boolean verticesSizeEquals = this.allVertices.size() == g.allVertices.size();
if (!verticesSizeEquals)
return false;
final boolean edgesSizeEquals = this.allEdges.size() == g.allEdges.size();
if (!edgesSizeEquals)
return false;
// Vertices can contain duplicates and appear in different order but both arrays should contain the same elements
final Object[] ov1 = this.allVertices.toArray();
Arrays.sort(ov1);
final Object[] ov2 = g.allVertices.toArray();
Arrays.sort(ov2);
for (int i=0; i<ov1.length; i++) {
final Vertex<T> v1 = (Vertex<T>) ov1[i];
final Vertex<T> v2 = (Vertex<T>) ov2[i];
if (!v1.equals(v2))
return false;
}
// Edges can contain duplicates and appear in different order but both arrays should contain the same elements
final Object[] oe1 = this.allEdges.toArray();
Arrays.sort(oe1);
final Object[] oe2 = g.allEdges.toArray();
Arrays.sort(oe2);
for (int i=0; i<oe1.length; i++) {
final Edge<T> e1 = (Edge<T>) oe1[i];
final Edge<T> e2 = (Edge<T>) oe2[i];
if (!e1.equals(e2))
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
for (Vertex<T> v : allVertices)
builder.append(v.toString());
return builder.toString();
}
public static class Vertex<T extends Comparable<T>> implements Comparable<Vertex<T>> {
private T value = null;
private int weight = 0;
private List<Edge<T>> edges = new ArrayList<Edge<T>>();
public Vertex(T value) {
this.value = value;
}
public Vertex(T value, int weight) {
this(value);
this.weight = weight;
}
/** Deep copies the edges along with the value and weight **/
public Vertex(Vertex<T> vertex) {
this(vertex.value, vertex.weight);
this.edges.addAll(vertex.edges);
}
public T getValue() {
return value;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void addEdge(Edge<T> e) {
edges.add(e);
}
public List<Edge<T>> getEdges() {
return edges;
}
public Edge<T> getEdge(Vertex<T> v) {
for (Edge<T> e : edges) {
if (e.to.equals(v))
return e;
}
return null;
}
public boolean pathTo(Vertex<T> v) {
for (Edge<T> e : edges) {
if (e.to.equals(v))
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int code = this.value.hashCode() + this.weight + this.edges.size();
return 31 * code;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object v1) {
if (!(v1 instanceof Vertex))
return false;
final Vertex<T> v = (Vertex<T>) v1;
final boolean weightEquals = this.weight == v.weight;
if (!weightEquals)
return false;
final boolean edgesSizeEquals = this.edges.size() == v.edges.size();
if (!edgesSizeEquals)
return false;
final boolean valuesEquals = this.value.equals(v.value);
if (!valuesEquals)
return false;
final Iterator<Edge<T>> iter1 = this.edges.iterator();
final Iterator<Edge<T>> iter2 = v.edges.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
// Only checking the cost
final Edge<T> e1 = iter1.next();
final Edge<T> e2 = iter2.next();
if (e1.cost != e2.cost)
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Vertex<T> v) {
final int valueComp = this.value.compareTo(v.value);
if (valueComp != 0)
return valueComp;
if (this.weight < v.weight)
return -1;
if (this.weight > v.weight)
return 1;
if (this.edges.size() < v.edges.size())
return -1;
if (this.edges.size() > v.edges.size())
return 1;
final Iterator<Edge<T>> iter1 = this.edges.iterator();
final Iterator<Edge<T>> iter2 = v.edges.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
// Only checking the cost
final Edge<T> e1 = iter1.next();
final Edge<T> e2 = iter2.next();
if (e1.cost < e2.cost)
return -1;
if (e1.cost > e2.cost)
return 1;
}
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Value=").append(value).append(" weight=").append(weight).append("\n");
for (Edge<T> e : edges)
builder.append("\t").append(e.toString());
return builder.toString();
}
}
public static class Edge<T extends Comparable<T>> implements Comparable<Edge<T>> {
private Vertex<T> from = null;
private Vertex<T> to = null;
private int cost = 0;
public Edge(int cost, Vertex<T> from, Vertex<T> to) {
if (from == null || to == null)
throw (new NullPointerException("Both 'to' and 'from' vertices need to be non-NULL."));
this.cost = cost;
this.from = from;
this.to = to;
}
public Edge(Edge<T> e) {
this(e.cost, e.from, e.to);
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public Vertex<T> getFromVertex() {
return from;
}
public Vertex<T> getToVertex() {
return to;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int cost = (this.cost * (this.getFromVertex().hashCode() * this.getToVertex().hashCode()));
return 31 * cost;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object e1) {
if (!(e1 instanceof Edge))
return false;
final Edge<T> e = (Edge<T>) e1;
final boolean costs = this.cost == e.cost;
if (!costs)
return false;
final boolean from = this.from.equals(e.from);
if (!from)
return false;
final boolean to = this.to.equals(e.to);
if (!to)
return false;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Edge<T> e) {
if (this.cost < e.cost)
return -1;
if (this.cost > e.cost)
return 1;
final int from = this.from.compareTo(e.from);
if (from != 0)
return from;
final int to = this.to.compareTo(e.to);
if (to != 0)
return to;
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[ ").append(from.value).append("(").append(from.weight).append(") ").append("]").append(" -> ")
.append("[ ").append(to.value).append("(").append(to.weight).append(") ").append("]").append(" = ").append(cost).append("\n");
return builder.toString();
}
}
public static class CostVertexPair<T extends Comparable<T>> implements Comparable<CostVertexPair<T>> {
private int cost = Integer.MAX_VALUE;
private Vertex<T> vertex = null;
public CostVertexPair(int cost, Vertex<T> vertex) {
if (vertex == null)
throw (new NullPointerException("vertex cannot be NULL."));
this.cost = cost;
this.vertex = vertex;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public Vertex<T> getVertex() {
return vertex;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (this.cost * ((this.vertex!=null)?this.vertex.hashCode():1));
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object e1) {
if (!(e1 instanceof CostVertexPair))
return false;
final CostVertexPair<?> pair = (CostVertexPair<?>)e1;
if (this.cost != pair.cost)
return false;
if (!this.vertex.equals(pair.vertex))
return false;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(CostVertexPair<T> p) {
if (p == null)
throw new NullPointerException("CostVertexPair 'p' must be non-NULL.");
if (this.cost < p.cost)
return -1;
if (this.cost > p.cost)
return 1;
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(vertex.getValue()).append(" (").append(vertex.weight).append(") ").append(" cost=").append(cost).append("\n");
return builder.toString();
}
}
public static class CostPathPair<T extends Comparable<T>> {
private int cost = 0;
private List<Edge<T>> path = null;
public CostPathPair(int cost, List<Edge<T>> path) {
if (path == null)
throw (new NullPointerException("path cannot be NULL."));
this.cost = cost;
this.path = path;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public List<Edge<T>> getPath() {
return path;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = this.cost;
for (Edge<T> e : path)
hash *= e.cost;
return 31 * hash;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CostPathPair))
return false;
final CostPathPair<?> pair = (CostPathPair<?>) obj;
if (this.cost != pair.cost)
return false;
final Iterator<?> iter1 = this.getPath().iterator();
final Iterator<?> iter2 = pair.getPath().iterator();
while (iter1.hasNext() && iter2.hasNext()) {
Edge<T> e1 = (Edge<T>) iter1.next();
Edge<T> e2 = (Edge<T>) iter2.next();
if (!e1.equals(e2))
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Cost = ").append(cost).append("\n");
for (Edge<T> e : path)
builder.append("\t").append(e);
return builder.toString();
}
}
}