给你一个由 '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
解:岛屿问题是DFS的网格类遍历问题
网格类的遍历都有一个基本的模板,通常都是采用递归每一个节点,然后判断边界节点
void cleanLand(char** grid,int gridSize,int ColSize,int row,int column)
{
if(grid[row][column]=='1')
grid[row][column]='0';
else return;
int newRow,newColumn;
if(row!=0)
{
newRow=row-1;
cleanLand(grid,gridSize,ColSize,newRow,column);
}
if(row!=gridSize-1)
{
newRow=row+1;
cleanLand(grid,gridSize,ColSize,newRow,column);
}
if(column!=0)
{
newColumn=column-1;
cleanLand(grid,gridSize,ColSize,row,newColumn);
}
if(column!=ColSize-1)
{
newColumn=column+1;
cleanLand(grid,gridSize,ColSize,row,newColumn);
}
}
int numIslands(char** grid, int gridSize, int* gridColSize) {
int row,column,ReturnLand=0;
for(row=0;row<gridSize;row++)
{
for(column=0;column<gridColSize[row];column++)
{
if(grid[row][column]=='1')
{
cleanLand(grid,gridSize,gridColSize[row],row,column);
ReturnLand++;
}
}
}
return ReturnLand;
}