200. Number of Islands
Topic link
Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-islands/ The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Title description
Given a two-dimensional grid composed of '1' (land) and '0' (water), please count the number of islands in the grid.
Islands are always surrounded by water, and each island can only be formed by connecting adjacent land in the horizontal and/or vertical direction.
In addition, you can assume that all four sides of the grid are 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
Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-islands
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Topic analysis
BFS-bfs generally use the
queue to store the first value and the second value of the array in the queue. The array is not placed.
Check grid[i][j] equal to 1 and find the position where the top, bottom, left, and right are also 1. In the queue
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
int m = grid.size();
int n = grid[0].size();
queue<int> queue;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
res++;
queue.push(i);
queue.push(j);
grid[i][j] = '0';
while(queue.size()){
int x = queue.front();
queue.pop();
int y = queue.front();
queue.pop();
if(x-1 >= 0 && grid[x-1][y] == '1'){
grid[x - 1][y] = '0';
queue.push(x-1);
queue.push(y);
}
if(x+1 < m &&grid[x+1][y] == '1'){
grid[x + 1][y] = '0';
queue.push(x+1);
queue.push(y);
}
if(y-1 >= 0 && grid[x][y-1] == '1'){
grid[x ][y-1] = '0';
queue.push(x);
queue.push(y-1);
}
if(y+1 < n && grid[x][y+1] == '1'){
grid[x][y+1] = '0';
queue.push(x);
queue.push(y+1);
}
}
}
}
}
return res;
}
};