This repository has been archived by the owner on Oct 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathDijkstra.kt
56 lines (48 loc) · 1.62 KB
/
Dijkstra.kt
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
class Dijkstra {
// Dijkstra's algorithm to find shortest path from s to all other nodes
fun dijkstra(G: WeightedGraph, s: Int): IntArray {
val dist = IntArray(G.size()) // shortest known distance from "s"
val pred = IntArray(G.size()) // preceeding node in path
val visited = BooleanArray(G.size()) // all false initially
for (i in dist.indices) {
dist[i] = Integer.MAX_VALUE
}
dist[s] = 0
for (i in dist.indices) {
val next = minVertex(dist, visited)
visited[next] = true
// The shortest path to next is dist[next] and via pred[next].
val n = G.neighbors(next)
for (j in n.indices) {
val v = n[j]
val d = dist[next] + G.getWeight(next, v)
if (dist[v] > d) {
dist[v] = d
pred[v] = next
}
}
}
return pred // (ignore pred[s]==0!)
}
private fun minVertex(dist: IntArray, v: BooleanArray): Int {
var x = Integer.MAX_VALUE
var y = -1 // graph not connected, or no unvisited vertices
for (i in dist.indices) {
if (!v[i] && dist[i] < x) {
y = i
x = dist[i]
}
}
return y
}
fun printPath(G: WeightedGraph, pred: IntArray, s: Int, e: Int) {
val path = java.util.ArrayList()
var x = e
while (x != s) {
path.add(0, G.getLabel(x))
x = pred[x]
}
path.add(0, G.getLabel(s))
System.out.println(path)
}
}