算法系列——岛屿数量
Posted BridgeGeorge
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法系列——岛屿数量相关的知识,希望对你有一定的参考价值。
题目
题目链接:力扣
给你一个由 '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
解法
岛屿类问题通用解法:力扣
class Solution
public int numIslands(char[][] grid)
int result=0;
int row=grid.length;
int col=grid[0].length;
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
if(grid[i][j]=='1')
result++;
dfs(grid,i,j);
return result;
void dfs(char[][] grid, int r, int c)
// 判断 base case
// 如果坐标 (r, c) 超出了网格范围,直接返回
if (!inArea(grid, r, c))
return;
// 如果这个格子不是岛屿,直接返回
if (grid[r][c] != '1')
return;
grid[r][c] = '2'; // 将格子标记为「已遍历过」
// 访问上、下、左、右四个相邻结点
dfs(grid, r - 1, c);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
dfs(grid, r, c + 1);
// 判断坐标 (r, c) 是否在网格中
boolean inArea(char[][] grid, int r, int c)
return 0 <= r && r < grid.length
&& 0 <= c && c < grid[0].length;
以上是关于算法系列——岛屿数量的主要内容,如果未能解决你的问题,请参考以下文章