-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
93 lines (71 loc) · 2.08 KB
/
Dijkstra.java
File metadata and controls
93 lines (71 loc) · 2.08 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
import java.lang.Math;
public class Dijkstra {
public void run(int n) {
int[][] graph = new int[n][n];
fillRandomGraph(graph);
print(graph);
Node[] myNodes = new Node[graph.length];
for(int i = 0; i < graph.length; i++) {
myNodes[i] = new Node(i);
}
dijkstra(graph, myNodes);
printPath(myNodes[2]);
}
public void print(int[][] graph) {
for(int i = 0; i < graph.length; i++) {
for(int j = 0; j < graph.length; j++) {
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
public void fillRandomGraph(int[][] graph) {
for(int i = 0; i < graph.length; i++) {
for(int j = i+1; j < graph.length; j++) {
double rand = Math.random();
if(rand < 0.8) {
graph[i][j] = (int)(Math.random() * 10);
graph[j][i] = graph[i][j];
}
else{
graph[i][j] = 0;
graph[j][i] = 0;
}
}
}
}
public static void main(String [] args) {
if(args.length > 0) new Dijkstra().run(Integer.parseInt(args[0]));
else new Dijkstra().run(6);
}
public void dijkstra (int [][] adjmatrix, Node [] nodes) {
Heap heap = new Heap ();
for(Node current : nodes) {
current.distance = Integer.MAX_VALUE;
current.parent = null;
heap.add(current);
}
nodes[0].distance = 0;
while(heap.size() != 0) {
Node u = heap.remove(); //shortest path to u, not you
for(int i = 0; i < adjmatrix.length; i ++) {
Node v = nodes[i];
if(adjmatrix[u.index][i] != 0 ) {
int newdistance = u.distance + adjmatrix[u.index][i];
if(newdistance < v.distance) {
v.distance = newdistance;
v.parent = u;
heap.decreaseKey(v, newdistance);
}
}
}
}
}
public void printPath (Node node) {
Node temp = node;
while (temp.index != 0) {
System.out.print(temp.index + " -> ");
temp = temp.parent;
}System.out.print(temp.index + "");
}
}