使用HashMap作为邻接表存储图实现最短路(Java)
作者:
三七二十七
,
2021-04-21 20:26:55
,
所有人可见
,
阅读 722
import java.util.*;
public class Main{
public static int INF = 0x3f3f3f3f;
public static int n;
public static Map<Integer, List<Node>> map = new HashMap<>();
public static int[] dist;
public static boolean[] st;
public static class Node {
public int node;
public int length;
public Node(int node, int length) {
this.node = node;
this.length = length;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
dist = new int[n + 1];
st = new boolean[n + 1];
for (int i = 1; i <= n ; i ++) {
map.put(i, new ArrayList<>());
}
int m = sc.nextInt();
for (int i = 0; i < m ; i ++ ) {
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
map.get(x).add(new Node(y, z));
}
int res = dijkstra();
System.out.println(res);
}
public static int dijkstra() {
for (int i = 1; i <= n ; i ++) {
dist[i] = INF;
}
dist[1] = 0;
for (int i = 0; i < n ; i ++ ) {
int t = 0;
for (int j = 1; j <= n; j ++ ) {
if(!st[j] && (t == 0 || dist[t] > dist[j])) t = j;
}
st[t] = true;
for (Node next : map.get(t)) {
int j = next.node;
int len = next.length;
dist[j] = Math.min(dist[j], dist[t] + len);
}
}
if(dist[n] == INF) {
return -1;
}
return dist[n];
}
}