Approach
Breadth-first search
For Last Day Where You Can Still Cross, 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
- 58 lines of Java from the credited upstream file 1970.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 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 latestDayToCross(int row, int col, int[][] cells) {3 int ans = 0;4 int l = 1;5 int r = cells.length - 1;6 7 while (l <= r) {8 final int m = (l + r) / 2;9 if (canWalk(m, row, col, cells)) {10 ans = m;11 l = m + 1;12 } else {13 r = m - 1;14 }15 }16 17 return ans;18 }19 20 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};21 22 private boolean canWalk(int day, int row, int col, int[][] cells) {23 int[][] matrix = new int[row][col];24 for (int i = 0; i < day; ++i) {25 final int x = cells[i][0] - 1;26 final int y = cells[i][1] - 1;27 matrix[x][y] = 1;28 }29 30 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();31 32 for (int j = 0; j < col; ++j)33 if (matrix[0][j] == 0) {34 q.offer(new Pair<>(0, j));35 matrix[0][j] = 1;36 }37 38 while (!q.isEmpty()) {39 final int i = q.peek().getKey();40 final int j = q.poll().getValue();41 for (int[] dir : DIRS) {42 final int x = i + dir[0];43 final int y = j + dir[1];44 if (x < 0 || x == row || y < 0 || y == col)45 continue;46 if (matrix[x][y] == 1)47 continue;48 if (x == row - 1)49 return true;50 q.offer(new Pair<>(x, y));51 matrix[x][y] = 1;52 }53 }54 55 return false;56 }57}58