题目描述
思路分析
当登陆某个岛屿后,以此时所处位置为行动中心,将当前坐标点置为0(避免重复计数),随后分别向 东、南、西、北 四个方向前进。如果向某一方向前进后其为水或登记的地方则停止探索,而当步入新地点时,则继续以当前所处位置为行动中心,随后再一次向 东、南、西、北 四个方向前进,以此类推。
代码实现
package LeetCode;
public class MaxAreaOfIsland {
public static void main(String[] args) {
}
public int maxAreaOfIsland(int[][] grid) {
int len = grid.length;
if (len == 0)
return 0;
int h = grid[0].length;
int max = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < h; j++) {
if (grid[i][j] == 1) {
int num = check(grid, i, j);
max = num > max ? num : max;
}
}
}
return max;
}
// check是一个递归方法,用DFS进行当前节点(x,y)相邻的(x-1,y),(x+1,y),(x,y-1),(x,y+1)的check
private int check(int[][] grid, int x, int y) {
int count = 1;
grid[x][y] = 0; // 如果当前节点已经检查过,则置0,不需要再检查
if (x - 1 >= 0 && grid[x - 1][y] == 1) {// 上面
count += check(grid, x - 1, y);
}
if (x + 1 < grid.length && grid[x + 1][y] == 1) {// 下面
count += check(grid, x + 1, y);
}
if (y - 1 >= 0 && grid[x][y - 1] == 1) {// 左面
count += check(grid, x, y - 1);
}
if (y + 1 < grid[0].length && grid[x][y + 1] == 1) {
count += check(grid, x, y + 1);
}
return count;
}
}