自我总结:虽然将DFS基本原理学懂,但做题时仍无法完美的使用
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
//标准代码:
void DFS(char** grid,int row,int col,int gridSize,int gridColSize)
{
if(grid[row][col]=='0') return;
grid[row][col]='0';
if(row!=0)
DFS(grid,row-1,col,gridSize,gridColSize);
if(row!=gridSize-1)
DFS(grid,row+1,col,gridSize,gridColSize);
if(col!=0)
DFS(grid,row,col-1,gridSize,gridColSize);
if(col!=gridColSize-1)
DFS(grid,row,col+1,gridSize,gridColSize);
}
int numIslands(char** grid, int gridSize, int* gridColSize)
{
int row,col,returnSize=0;
for(row=0;row<gridSize;row++)
for(col=0;col<gridColSize[row];col++)
if(grid[row][col]=='1')
{
returnSize++;//用于记录有多少个“岛屿”
DFS(grid,row,col,gridSize,gridColSize[row]);
}
return returnSize;
}
在主函数依次从左到右,从上到下遍历,每当遇到1时,就从主函数里调用DFS函数,将多个连续相连的1全部改为0 ;DFS函数里,判断每一个点是否为1,不为1则返回,否则为1接着判断该点1的上下左右所有的点,依次递归,直到相连的1都变成0则退出DFS函数,然后在主函数的循环里接着寻找下一个为1的点,该点是一个新的岛屿;循环以上步骤,直到遍历完每一个岛屿。