Approach
Breadth-first search
For Minimum Time to Visit a Cell In a Grid, 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
- 38 lines of Java from the credited upstream file 2577.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 minimumTime(int[][] grid) {3 if (grid[0][1] > 1 && grid[1][0] > 1)4 return -1;5 6 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};7 final int m = grid.length;8 final int n = grid[0].length;9 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {10 { offer(new int[] {0, 0, 0}); } 11 };12 boolean[][] seen = new boolean[m][n];13 seen[0][0] = true;14 15 while (!minHeap.isEmpty()) {16 final int time = minHeap.peek()[0];17 final int i = minHeap.peek()[1];18 final int j = minHeap.poll()[2];19 if (i == m - 1 && j == n - 1)20 return time;21 for (int[] dir : DIRS) {22 final int x = i + dir[0];23 final int y = j + dir[1];24 if (x < 0 || x == m || y < 0 || y == n)25 continue;26 if (seen[x][y])27 continue;28 final int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0;29 final int nextTime = Math.max(time + 1, grid[x][y] + extraWait);30 minHeap.offer(new int[] {nextTime, x, y});31 seen[x][y] = true;32 }33 }34 35 throw new IllegalArgumentException();36 }37}38