-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
48 lines (46 loc) · 1.41 KB
/
Dijkstra.java
File metadata and controls
48 lines (46 loc) · 1.41 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
import java.util.*;
public class Dijkstra {
public static void main(String[] args)
{
int num = 10; // change to number of nodes
Comparator<int[]> c = new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2)
{
return o1[0] - o2[0]; //ascending by distance
}
};
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(c);
ArrayList<ArrayList<Integer>> AdjList = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> weights = new ArrayList<ArrayList<Integer>>();
//initialize adjacency list
int[] distances = new int[num];
int[] path = new int[num];
Arrays.fill(distances, Integer.MAX_VALUE);
int source = 0;
int endpoint = 1; //beginning and ending of path
distances[source] = 0;
path[source] = source;
pq.add(new int[] {0, source});
int[] el;
ArrayList<Integer> edges;
while (!pq.isEmpty())
{
el = pq.poll();
if (el[0] > distances[el[1]]) //if we already got to this point with a path that is more optimal, don't even relax this one's edges, because it couldn't be on the shortest path.
continue;
if (el[1] == endpoint)
break;
edges = AdjList.get(el[1]);
for (int i = 0; i < edges.size(); i++)
{
if (el[0] + weights.get(el[1]).get(i) < distances[edges.get(i)])
{
distances[edges.get(i)] = el[0] + weights.get(el[1]).get(i);
path[edges.get(i)] = el[1];
pq.add(new int[] {distances[edges.get(i)], i});
}
}
}
}
}