Tuesday, March 22, 2022

LeetCode 200. 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.

 

Example 1:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

class Solution {
public:
vector<vector<bool>> seen;
vector<vector<char>> grid;
int m, n;
int ans = 0;
// travel through island
void bfs(int i, int j){
queue<pair<int, int>> que;
que.emplace(i, j);
seen[i][j] = true;
while(!que.empty()){
int x = que.front().first;
int y = que.front().second;
que.pop();
for(int dx = -1; dx <= 1; dx++){
for(int dy = -1; dy <= 1; dy++){
if(abs(dx + dy) != 1) continue;
int nx = x + dx;
int ny = y + dy;
if(nx < 0 or nx >= m or ny < 0 or ny >= n or
seen[nx][ny] or grid[nx][ny] == '0') continue;
que.emplace(nx, ny);
seen[nx][ny] = true;
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
n = grid[0].size();
this->grid = grid;
seen.resize(m, vector<bool>(n, false));
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(grid[i][j] == '1' and !seen[i][j]){
bfs(i, j);
ans++;
}
return ans;
}
};

No comments:

Post a Comment