Approach
Breadth-first search
For Second Minimum Time to Reach Destination, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 46 lines of Java from the credited upstream file 2045.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int secondMinimum(int n, int[][] edges, int time, int change) {3 List<Integer>[] graph = new List[n + 1];4 5 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(1, 0)));6 7 8 int[][] minTime = new int[n + 1][2];9 Arrays.stream(minTime).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));10 minTime[1][0] = 0;11 12 for (int i = 1; i <= n; ++i)13 graph[i] = new ArrayList<>();14 15 for (int[] edge : edges) {16 final int u = edge[0];17 final int v = edge[1];18 graph[u].add(v);19 graph[v].add(u);20 }21 22 while (!q.isEmpty()) {23 final int u = q.peek().getKey();24 final int prevTime = q.poll().getValue();25 26 27 28 final int numChangeSignal = prevTime / change;29 final int waitTime = numChangeSignal % 2 == 0 ? 0 : change - prevTime % change;30 final int newTime = prevTime + waitTime + time;31 for (final int v : graph[u])32 if (newTime < minTime[v][0]) {33 minTime[v][0] = newTime;34 q.offer(new Pair<>(v, newTime));35 } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) {36 if (v == n)37 return newTime;38 minTime[v][1] = newTime;39 q.offer(new Pair<>(v, newTime));40 }41 }42 43 throw new IllegalArgumentException();44 }45}46