
Solution BFS
- we will perform a level-wise BFS iteration over the nodes
- level limited by k
- cost[] stores the minimum price to reach each node
- if next adj costs more than min, dont explore

class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
for (int[] flight : flights) {
int from = flight[0], to = flight[1], cost = flight[2];
if (!graph.containsKey(from)) {
graph.put(from, new HashMap<>());
}
graph.get(from).put(to, cost);
}
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] {src, 0});
int stops = 0;
int[] minCost = new int[n];
Arrays.fill(minCost, Integer.MAX_VALUE);
while (stops <= k && !queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
int curCity = cur[0];
int curCost = cur[1];
if (!graph.containsKey(curCity)) {
continue;
}
for (Map.Entry<Integer, Integer> entry : graph.get(curCity).entrySet()) {
int nextCity = entry.getKey();
int cost = entry.getValue();
if (minCost[nextCity] > curCost + cost) {
minCost[nextCity] = curCost + cost;
queue.offer(new int[] { nextCity, minCost[nextCity] });
}
}
}
stops++;
}
return minCost[dst] == Integer.MAX_VALUE ? -1 : minCost[dst];
}
}