|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.PriorityQueue; |
| 7 | + |
| 8 | +public class _3112 { |
| 9 | + public static class Solution1 { |
| 10 | + /** |
| 11 | + * My completely original solution: Dijkstra's algorithm! |
| 12 | + */ |
| 13 | + public int[] minimumTime(int n, int[][] edges, int[] disappear) { |
| 14 | + List<int[]>[] graph = new ArrayList[n]; |
| 15 | + for (int i = 0; i < n; i++) { |
| 16 | + graph[i] = new ArrayList<>(); |
| 17 | + } |
| 18 | + for (int[] edge : edges) { |
| 19 | + graph[edge[0]].add(new int[]{edge[1], edge[2]}); |
| 20 | + graph[edge[1]].add(new int[]{edge[0], edge[2]}); |
| 21 | + } |
| 22 | + int[] ans = new int[n]; |
| 23 | + int[] shortestTimes = new int[disappear.length]; |
| 24 | + Arrays.fill(shortestTimes, Integer.MAX_VALUE); |
| 25 | + shortestTimes[0] = 0; |
| 26 | + dijkstra(graph, disappear, shortestTimes); |
| 27 | + for (int target = 1; target < n; target++) { |
| 28 | + if (shortestTimes[target] == Integer.MAX_VALUE || shortestTimes[target] >= disappear[target]) { |
| 29 | + ans[target] = -1; |
| 30 | + } else { |
| 31 | + ans[target] = shortestTimes[target]; |
| 32 | + } |
| 33 | + } |
| 34 | + return ans; |
| 35 | + } |
| 36 | + |
| 37 | + private void dijkstra(List<int[]>[] graph, int[] disappear, int[] shortestTimes) { |
| 38 | + PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[1] - b[1]); |
| 39 | + q.offer(new int[]{0, 0}); |
| 40 | + while (!q.isEmpty()) { |
| 41 | + int[] curr = q.poll(); |
| 42 | + int currNode = curr[0]; |
| 43 | + int currCost = curr[1]; |
| 44 | + if (currCost > shortestTimes[currNode]) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + for (int[] neighbor : graph[currNode]) { |
| 48 | + int neighborNode = neighbor[0]; |
| 49 | + int neighborCost = neighbor[1]; |
| 50 | + if (neighborCost + currCost < shortestTimes[neighborNode] && neighborCost + currCost < disappear[neighborNode]) { |
| 51 | + shortestTimes[neighborNode] = neighborCost + currCost; |
| 52 | + q.offer(new int[]{neighborNode, shortestTimes[neighborNode]}); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments