Re: [闲聊] 每日leetcode

楼主: DJYOMIYAHINA (通通打死)   2024-08-11 22:18:39
想不到
直接看hint 很简洁明了
最多两个0就可以切出一个独立的island
我怎么没想到
我是智障
class Solution {
public:
int m;
int n;
void dfs(vector<vector<int>>& grid, int i, int j) {
if (grid[i][j] == -1 || grid[i][j] == 0) {
return;
}
grid[i][j] = -1;
int delta[5] = {0, 1, 0, -1, 0};
for (int k=0; k<4; k++) {
int next_i = i+delta[k];
int next_j = j+delta[k+1];
if (0<=next_i && next_i<this->m && 0<=next_j && next_j<this->n) {
dfs(grid, next_i, next_j);
}
}
return;
}
int numofIsland(vector<vector<int>>& grid) {
int num = 0;
for (int i=0; i<this->m; i++) {
for (int j=0; j<this->n; j++) {
if (grid[i][j] == 1) {
dfs(grid, i, j);
num += 1;
}
}
}
// reset grid
for (int i=0; i<this->m; i++) {
for (int j=0; j<this->n; j++) {
if (grid[i][j] == -1) {
grid[i][j] = 1;
}
}
}
return num;
}
int minDays(vector<vector<int>>& grid) {
this->m = grid.size();
this->n = grid[0].size();
if (numofIsland(grid) != 1) {
return 0;
}
for(int i=0; i<this->m; i++) {
for(int j=0; j<this->n; j++) {
if(grid[i][j] == 1) {
grid[i][j] = 0;
if (numofIsland(grid) != 1) {
return 1;
}
grid[i][j] = 1;
}
}
}
return 2;
}
};
作者: Smallsh (Smallsh)   2024-08-11 22:20:00
大师
作者: JIWP (JIWP)   2024-08-11 22:21:00
别倦了
作者: sustainer123 (caster)   2024-08-11 22:21:00
大师
作者: rainkaras (rainkaras)   2024-08-11 23:06:00
7
作者: oin1104 (是oin的说)   2024-08-11 23:13:00
大师
作者: dont   2024-08-12 01:01:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com