[LeetCode] Number of Islands

200. Number of Islands

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

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
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0, dx[4]{0,1,0,-1}, dy[4]{-1,0,1,0}, n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] & 0b1111) {
res++;
queue<pair<int, int>> q;
q.push({i,j});
grid[i][j] = 48;
while(!q.empty()) {
auto p = q.front();
q.pop();
for(int k = 0; k < 4; k++) {
int nx = p.second + dx[k], ny = p.first + dy[k];
if(0 <= nx && nx < m && 0 <= ny && ny < n && grid[ny][nx] & 0b1111) {
q.push({ny,nx});
grid[ny][nx] = 48;
}
}
}
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/number-of-islands/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.