Number of Islands
Problem
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.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
vector<vector<char>> g;
int m, n;
public:
void dfs(int i, int j) {
if (i >= n || j >= m || j < 0 || i < 0) return;
if (g[i][j] == '2' || g[i][j] == '0') return;
g[i][j] = '2';
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
for (int k = 0; k < 4; k++) {
dfs(i + dx[k], j + dy[k]);
}
}
int numIslands(vector<vector<char>>& grid) {
this->g = grid;
n = grid.size();
m = grid[0].size();
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '1') {
ans++;
dfs(i, j);
}
}
}
return ans;
}
};