Approach
Breadth-first search
For Find Minimum Time to Reach Last Room I, 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
- 45 lines of Java from the credited upstream file 3341.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 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 minTimeToReach(int[][] moveTime) {3 return dijkstra(moveTime, new Pair<>(0, 0),4 new Pair<>(moveTime.length - 1, moveTime[0].length - 1));5 }6 7 private int dijkstra(int[][] moveTime, Pair<Integer, Integer> src, Pair<Integer, Integer> dst) {8 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};9 final int m = moveTime.length;10 final int n = moveTime[0].length;11 int[][] dist = new int[m][n];12 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));13 14 dist[0][0] = 0;15 Queue<Pair<Integer, Pair<Integer, Integer>>> minHeap =16 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {17 { offer(new Pair<>(dist[0][0], src)); } 18 };19 20 while (!minHeap.isEmpty()) {21 final int d = minHeap.peek().getKey();22 final Pair<Integer, Integer> u = minHeap.poll().getValue();23 if (u.equals(dst))24 return d;25 final int i = u.getKey();26 final int j = u.getValue();27 if (d > dist[i][j])28 continue;29 for (int[] dir : DIRS) {30 final int x = i + dir[0];31 final int y = j + dir[1];32 if (x < 0 || x == m || y < 0 || y == n)33 continue;34 final int newDist = Math.max(moveTime[x][y], d) + 1;35 if (newDist < dist[x][y]) {36 dist[x][y] = newDist;37 minHeap.offer(new Pair<>(newDist, new Pair<>(x, y)));38 }39 }40 }41 42 return -1;43 }44}45