695. Max Area of Island
Given a non-empty 2D array grid
of 0's and 1's, an island is a group of 1
's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
一開始的想法是如果找到陣列在迴圈中的找尋順序為左到右、上到下,所以當找到數值為 1 的,就先檢查改數值的上面和左邊是否也為 1 ,若上面和左邊都不是 1 的話,就代表該數值是第一次被找到,接著就可以以此點為基準,往右和往下坐遞迴或迴圈
後來在討論區發現將搜尋過的數值改成 0,就可以保證不會再計算到了,所以就改寫成了下面的方法
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int max = 0;
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid[i].length; j++) {
if(grid[i][j] == 1) {
max = Math.max(getArea(grid, i, j), max);
}
}
}
return max;
}
private int getArea(int[][] grid, int i, int j) {
if(i < 0 || j < 0 || i > grid.length - 1 || j > grid[i].length - 1 || grid[i][j] == 0) {
return 0;
} else {
grid[i][j] = 0;
return 1 + getArea(grid, i + 1, j) + getArea(grid, i, j + 1) + getArea(grid, i - 1, j) + getArea(grid, i, j - 1);
}
}
}