求岛屿的最大面积
给定一个包含了一些 0 和 1 的非空二维数组 grid 。
一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)
示例 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。
思路:
我们先从第一个岛屿出发,因为需要判断岛屿(也就是1)是连续的,在一个方向一直走到尾很明显符合深度优先遍历,需要深度优先遍历对每个岛屿进行遍历,直到遇到水(也就是0)。
遍历某一岛屿时:
1.向四个方向递归dfs。
2.每次递归对下标进行判断,注意边界问题。
3.对每块访问过的岛屿置0,防止重复访问。
4.递归返回整块陆地的面积。
static int count = 0;
static int res = 0;
static int rows ,cols;
static int[][] result;
public static int calculation(int[][] area){
if(area.length < 0) return 0;
result = area;
rows = area.length;
cols = area[0].length;
for(int i = 0 ; i < rows; i++){
for(int j = 0; j < cols; j++){
dfs(i,j);
count = 0;
}
}
return res;
}
private static void dfs(int i, int j) {
if(i < 0 || j < 0 || i >= rows || j >= cols || result[i][j] == 0){
res = Math.max(res,count);
return;
}
count++;
result[i][j] = 0;
dfs(i+1,j);
dfs(i-1,j);
dfs(i,j+1);
dfs(i,j-1);
}
测试一下:
public static void main(String[] args) {
int[][] arr = new int[][]{{0,0,1,0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,1,1,0,1,0,0,0,0,0,0,0,0},
{0,1,0,0,1,1,0,0,1,0,1,0,0},
{0,1,0,0,1,1,0,0,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,0,0}};
int calculation = calculation(arr);
System.out.println(calculation);
}