1928. Minimum Cost to Reach Destination in Time

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public int minCost(int maxTime, int[][] edges, int[] passingFees) {
        List<List<int[]>> graph = new ArrayList<>();
        int n = passingFees.length;
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            int from = edge[0], to = edge[1], fee = edge[2];
            graph.get(from).add(new int[]{to, fee});
            graph.get(to).add(new int[]{from, fee});
        }
        // priority, time, node
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        heap.offer(new int[]{passingFees[0], 0, 0});
        int[] minTime = new int[n];
        Arrays.fill(minTime, Integer.MAX_VALUE);

        while (!heap.isEmpty()) {
            int[] cur = heap.poll();
            int curCost = cur[0], curTime = cur[1], curNode = cur[2];
            if (curNode == n - 1) {
                return curCost;
            }

            for (int[] neigh : graph.get(curNode)) {
                int nextNode = neigh[0], nextTime = neigh[1];
                if (nextTime + curTime > maxTime || 
                nextTime + curTime >= minTime[nextNode]) continue;
                minTime[nextNode] = nextTime + curTime;
                heap.offer(new int[]{curCost + passingFees[nextNode], 
                nextTime + curTime, nextNode});
            }
        }
        return -1;
    }
}