[AlgoExpert] Remove Islands

Remove Islands

  • Time : O(nm)
  • Space : O(n+m)
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
void bfs(vector<vector<int>>& matrix, int sy, int sx) {
int n = matrix.size(), m = matrix[0].size();
int dy[4]{-1,0,1,0},dx[4]{0,1,0,-1};
queue<pair<int,int>> q;
q.push({sy,sx});
matrix[sy][sx] = -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] == 1) {
matrix[ny][nx] = -1;
q.push({ny,nx});
}
}
}
}
vector<vector<int>> removeIslands(vector<vector<int>> matrix) {
int n = matrix.size(), m = matrix[0].size();
for(int i = 0; i < n; i++) {
if(matrix[i][0] == 1) bfs(matrix, i, 0);
if(matrix[i][m-1] == 1) bfs(matrix, i, m-1);
}
for(int i = 0; i < m; i++) {
if(matrix[0][i] == 1) bfs(matrix, 0, i);
if(matrix[n-1][i] == 1) bfs(matrix, n-1, i);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(matrix[i][j] == -1) matrix[i][j] = 1;
else if(matrix[i][j] == 1) matrix[i][j] = 0;
}
}

return matrix;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/16/PS/AlgoExpert/remove-islands/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.