695岛屿的最大面积-数组
描述
给定一个包含了一些 0 和 1的非空二维数组 grid
, 一个 岛屿 是由四个方向 (水平或垂直) 的 1
(代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
实例
[[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
[[0,0,0,0,0,0,0,0]]
输出:0
题解
首先遍历所有元素,如果值为1就开始判断这个岛屿的大小.
初始化一个栈,将当前元素放入栈中,并修改值为2,只要栈不空就持续从栈中取出一个元素,将值修改为2,并查看他的上下左右四个元素是否为1(探索过的陆地值为2).
static public int maxAreaOfIsland(int[][] grid) {
int W = grid[0].length;
int H = grid.length;
ArrayList<Integer> maxGrid = new ArrayList<>();
int max = 0;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (grid[i][j] == 0)
continue;
else if (grid[i][j] == 1){
Stack<Point> stack = new Stack<>();
stack.push(new Point(i,j));
grid[i][j] = 2;
Point nowPoint;
int x;
int y;
int counter = 0;
while (!stack.empty()){
nowPoint = stack.pop();
counter++;
x = nowPoint.x;
y = nowPoint.y;
if ((x > 0)){//边界判断,存入栈时就将值修改为2
if (grid[x-1][y] == 1){
stack.push(new Point(x-1,y));
grid[x-1][y] = 2;
}
}
if ((y < W-1)){
if (grid[x][y+1] == 1){
stack.push(new Point(x,y+1));
grid[x][y+1] = 2;
}
}
if ((y > 0)){
if (grid[x][y-1] == 1){
stack.push(new Point(x,y-1));
grid[x][y-1] = 2;
}
}
if ((x < H-1) ){
if (grid[x+1][y] == 1){
stack.push(new Point(x+1,y));
grid[x+1][y] = 2;
}
}
}
max = Math.max(max,counter);
}
}
}
// Collections.sort(maxGrid);
// if (maxGrid.size() == 0)
// return 0;
// else
// return maxGrid.get(maxGrid.size()-1);
return max;
其中被注释代码是第一个版本,将所有的岛屿面积都统计出来,再求最大值.但这样的速度太慢了,于是就没求出一个岛屿面积就与当前最大值比较并输出.
对于List类
,可以使用Collections
进行类似排序,求最大值之类的辅助操作.