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
- 60 lines of C++ from the credited upstream file 1970.cpp.
- 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:3 int latestDayToCross(int row, int col, vector<vector<int>>& cells) {4 int ans = 0;5 int l = 1;6 int r = cells.size() - 1;7 8 while (l <= r) {9 const int m = (l + r) / 2;10 if (canWalk(m, row, col, cells)) {11 ans = m;12 l = m + 1;13 } else {14 r = m - 1;15 }16 }17 18 return ans;19 }20 21 private:22 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};23 24 bool canWalk(int day, int row, int col, const vector<vector<int>>& cells) {25 vector<vector<int>> matrix(row, vector<int>(col));26 for (int i = 0; i < day; ++i) {27 const int x = cells[i][0] - 1;28 const int y = cells[i][1] - 1;29 matrix[x][y] = 1;30 }31 32 queue<pair<int, int>> q;33 34 for (int j = 0; j < col; ++j)35 if (matrix[0][j] == 0) {36 q.emplace(0, j);37 matrix[0][j] = 1;38 }39 40 while (!q.empty()) {41 const auto [i, j] = q.front();42 q.pop();43 for (const auto& [dx, dy] : kDirs) {44 const int x = i + dx;45 const int y = j + dy;46 if (x < 0 || x == row || y < 0 || y == col)47 continue;48 if (matrix[x][y] == 1)49 continue;50 if (x == row - 1)51 return true;52 q.emplace(x, y);53 matrix[x][y] = 1;54 }55 }56 57 return false;58 }59};60