Dijkstra’s algorithm finds the shortest path between a given node (which is called the “source node”) and all other nodes in a graph. This algorithm uses the weights of the edges to find the path that minimizes the total distance (weight) between the source node and all other nodes.
檢查是否存在一條路徑從 place 到 i ->g[place][i] > 0
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] g = new int[n][n];
for (int[] f : flights) {
g[f[0]][f[1]] = f[2];
}
// (1) adding the distance array to track min price to each node
int[] distance = new int[n];
Arrays.fill(distance, Integer.MAX_VALUE );
// (2) change heap to normal queue
Queue<int[]> heap = new LinkedList<>();
heap.offer(new int[]{0, src, K + 1});
distance[src] = 0;
while (!heap.isEmpty()) {
int[] cur = heap.poll();
int price = cur[0], place = cur[1], remainStops = cur[2];
if (remainStops > 0) {
for (int i = 0; i < n; i++) {
if (g[place][i] > 0 && distance[i] >= price + g[place][i]) {
heap.offer(new int[]{price + g[place][i], i, remainStops - 1});
distance[i] = Math.min(distance[i], price + g[place][i]);
}
}
}
}
return distance[dst] == Integer.MAX_VALUE ? -1 : distance[dst];
}
}
Time: O(E * K),其中 E 是邊的數量,K 是最大停止數。這是因為在最壞情況下,我們可能需要遍歷每條邊 K 次,以找到最短路徑 Space: O(N + E),其中 N 是節點數,E 是邊的數量。我們使用了一個 distance 數組來存儲每個節點到起點的最短距離,