[Geeks for Geeks] Find the number of islands

Find the number of islands

Given a grid of size n*m (n is number of rows and m is number of columns grid has) consisting of ‘0’s(Water) and ‘1’s(Land). Find the number of islands.

Note: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.

  • Time : O(nm)
  • Space : O(nm)
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
class Solution {
void bfs(vector<vector<char>>& grid, int sy, int sx, int n, int m) {
int dy[8]{-1,-1,-1,0,1,1,1,0}, dx[8]{-1,0,1,1,1,0,-1,-1};
queue<pair<int, int>> q;
q.push({sy, sx});
grid[sy][sx] = '0';
while(!q.empty()) {
auto p = q.front(); q.pop();
auto y = p.first, x = p.second;
for(int i = 0; i < 8; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and grid[ny][nx] == '1') {
grid[ny][nx] = '0';
q.push({ny,nx});
}
}
}
}
public:
// Function to find the number of islands.
int numIslands(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size();
int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == '1') {
bfs(grid, i, j, n, m);
res++;
}
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/find-the-number-of-islands/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.