一、题目描述
给你一个由 '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
二、解题思路
深度优先遍历:设置isVisited[]数组标记二维数组中当前位置的元素是否被访问;利用二重循环对二维数组进行遍历,如果当前的grid[i][j]='1'且isVisited[i][j]=false,则以当前元素为起点进行深度优先遍历(广度优先遍历也可),进行dfs的次数即为“岛屿”数。
三、代码实现
class Solution {
public int numIslands(char[][] grid) {
int row = grid.length;
int col = grid[0].length;
//标记是否被访问过
boolean[][] isVisited = new boolean[row][col];
//记录岛屿数
int islandCnt = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1' && !isVisited[i][j]) {
islandCnt++;
//以其为中心进行深度优先遍历
dfs(grid, isVisited, i, j);
}
}
}
return islandCnt;
}
public void dfs(char[][] grid, boolean[][] isVisited, int i, int j) {
int row = grid.length;
int col = grid[0].length;
if ( i == row || j == col || i == -1 || j == -1|| grid[i][j] =='0'||isVisited[i][j]) {
return;
}
isVisited[i][j]=true;
//深度优先遍历时,右、下、左、上四个方向
int[][] directions = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
for (int m = 0; m < 4; m++) {
int rowIndex = i + directions[m][0];
int colIndex = j + directions[m][1];
dfs(grid, isVisited, rowIndex, colIndex);
}
}
}