一、Dijkstra
public int networkDelayTime(int[][] times, int n, int k) {
int inf=0x3f3f3f3f;
int[][] weight=new int[n+1][n+1];
int[] distance=new int[n+1];
int[] visited=new int[n+1];
HashMap<Integer,List<Integer>> map=new HashMap<>();
for (int i=1;i<=n;i++){
map.put(i,new ArrayList<>());
}
for (int[] time:times){
int x=time[0];
int y=time[1];
weight[x][y]=time[2];
map.get(x).add(y);
}
PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1]-o2[1];
}
});
Arrays.fill(distance,inf);
distance[k]=0;
pq.add(new int[]{k,0});
while (!pq.isEmpty()){
int[] temp=pq.poll();
int base=temp[0];
int dis=temp[1];
if (visited[base]==1){
continue;
}
visited[base]=1;
distance[base]=dis;
for (int x:map.get(base)){
if (visited[x]==0&&dis+weight[base][x]<distance[x]){
pq.add(new int[]{x,dis+weight[base][x]});
}
}
}
int ans = 0;
for (int i = 1; i < distance.length; i++) {
int t = distance[i];
if (t >=inf) {
return -1;
}
ans = Math.max(ans, t);
}
return ans;
}
二、邻接矩阵
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
int[][] ws = new int[101][101];
Map<Integer, List<Integer>> edges = new HashMap<>();
for (int i = 1; i <= n; i++) {
edges.put(i, new ArrayList<>());
}
for (int i = 0; i < times.length; i++) {
int[] time = times[i];
int u = time[0], v = time[1], w = time[2];
ws[u][v] = w;
edges.get(u).add(v);
}
int[] arrival = new int[n + 1];
Arrays.fill(arrival, Integer.MAX_VALUE);
arrival[k] = 0;
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
queue.add(new int[] { k, 0 });
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int u = cur[0], w = cur[1];
if (w > arrival[u]) {
continue;
}
arrival[u]=w;
List<Integer> nexts = edges.get(u);
for (int next : nexts) {
int t = w + ws[u][next];
if (t < arrival[next]) {
queue.add(new int[] { next, t });
}
}
}
int ans = 0;
for (int i = 1; i < arrival.length; i++) {
int t = arrival[i];
if (t == Integer.MAX_VALUE) {
return -1;
}
ans = Math.max(ans, t);
}
return ans;
}
}