Leetcode 200 岛屿数量
岛屿数量(Number of Islands)
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
的值为'0'
或'1'
我们找到一个岛屿之后就把他清零,当所有数字都为0时,就表示结束了
const char WATER = '0';
const char LAND = '1';
const char NEW = 'X';
const char USED = 'O';
void floodFill(char** grid,int NUMBER_OF_ROWS,int NUMBER_OF_COLS,int i,int j){
if(i<0 || i>=NUMBER_OF_ROWS || j<0 || j>=NUMBER_OF_COLS||grid[i][j]!=LAND)return;
grid[i][j] = NEW;
floodFill(grid,NUMBER_OF_ROWS,NUMBER_OF_COLS,i-1,j);
floodFill(grid,NUMBER_OF_ROWS,NUMBER_OF_COLS,i+1,j);
floodFill(grid,NUMBER_OF_ROWS,NUMBER_OF_COLS,i,j-1);
floodFill(grid,NUMBER_OF_ROWS,NUMBER_OF_COLS,i,j+1);
}
int numIslands(char** grid, int gridSize, int* gridColSize){
if (gridSize == 0) return 0;
char q = grid[0][0];
const int NUMBER_OF_ROWS = gridSize;
const int NUMBER_OF_COLS = gridColSize[0];
int numberOfRegions = 0;
for (int i =0;i<NUMBER_OF_ROWS;i++){
for(int j =0;j<NUMBER_OF_COLS;j++){
if(grid[i][j] == LAND){
floodFill(grid,NUMBER_OF_ROWS,NUMBER_OF_COLS,i,j);
for(int y =0;y<NUMBER_OF_ROWS;y++){
for(int x=0;x<NUMBER_OF_COLS;x++){
if(grid[y][x]==NEW) {
grid[y][x]=USED;
}
}
}
numberOfRegions++;
}
}
}
return numberOfRegions;
}