[LeetCode] Last Day Where You Can Still Cross

1970. Last Day Where You Can Still Cross

There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.

Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).

You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).

Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
bool connected(vector<vector<bool>>& matrix, int n, int m) {
queue<pair<int,int>> q;
for(int i = 0; i < m; i++)
if(!matrix[0][i]) {
q.push({0,i});
matrix[0][i] = true;
}
int dy[4] = {-1,0,1,0}, dx[4] = {0,1,0,-1};
while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !matrix[ny][nx]) {
if(ny == n - 1) return true;
matrix[ny][nx] = true;
q.push({ny,nx});
}
}
}

return false;
}
public:
int latestDayToCross(int row, int col, vector<vector<int>>& cells) {
int l = 0, r = cells.size() - 1;
while(l <= r) {
int m = (l + r) / 2;

vector<vector<bool>> matrix(row, vector<bool>(col, false));
for(int i = 0; i <= m; i++)
matrix[cells[i][0] - 1][cells[i][1] - 1] = true;

if(connected(matrix, row, col)) l = m + 1;
else r = m - 1;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/LeetCode/last-day-where-you-can-still-cross/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.