-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestPath.java
More file actions
66 lines (62 loc) · 2.13 KB
/
Copy pathShortestPath.java
File metadata and controls
66 lines (62 loc) · 2.13 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
import java.util.*;
public class ShortestPath{
public static void main(String[] args){
int[][] matrix = {
{0, 2, 10, 0, 0, 0},
{2, 0, 1, 10, 0, 0},
{10, 1, 0, 5, 1, 0},
{0, 10, 5, 0, 2, 1},
{0, 0, 1, 2, 0, 0},
{0, 0, 0, 1, 0, 0}
};
int start = Integer.valueOf(args[0]);
int end = Integer.valueOf(args[1]);
List<Integer> ans = shortest(matrix, start, end);
for(int i=ans.size()-1; i>=0; i--)
System.out.println(ans.get(i));
}
public static List<Integer> shortest(int[][] matrix, int start, int end){
Map<Integer, List<int[]>> graph = new HashMap<>();
buildGraph(graph, matrix);
List<Integer> ans = new ArrayList<>();
int[] parent = new int[matrix.length];
int[] dist = new int[matrix.length];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
for(int i=0; i<matrix.length; i++)
parent[i] = i;
//PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{start, 0});
while(!queue.isEmpty()){
int[] cur = queue.poll();
int num = cur[0];
int time = cur[1];
for(int[] n : graph.get(num)){
if(dist[n[0]] > n[1] + time){
dist[n[0]] = n[1] + time;
queue.offer(new int[] {n[0], n[1]+time});
parent[n[0]] = num;
}
}
}
int c = end;
while(parent[c] != c){
ans.add(c);
c = parent[c];
}
ans.add(c);
return ans;
}
public static void buildGraph(Map<Integer, List<int[]>> graph, int[][] matrix){
for(int i=0; i<matrix.length; i++){
graph.put(i, new ArrayList<>());
}
for(int i=0; i<matrix.length; i++){
for(int j=0; j<matrix.length; j++){
if(matrix[i][j] != 0)
graph.get(i).add(new int[]{j, matrix[i][j]});;
}
}
}
}