给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为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]]
这道题可以参考 LeetCode 200 岛屿数量
两题类似,需要根据求得的目标的不同修改代码。
dfs
dfs
class Solution {
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int max = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
max = Math.max(dfs(grid, i, j), max);
}
}
}
return max;
}
private int dfs(int[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
int count = 1;
count = count + dfs(grid, i+1, j);
count = count + dfs(grid, i, j+1);
count = count + dfs(grid, i, j-1);
count = count + dfs(grid, i-1, j);
return count;
}
}
bfs
class Solution {
int[] dx = new int[]{0, 0, 1, -1};
int[] dy = new int[]{1, -1, 0, 0};
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int max = 0;
boolean[][] marked = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == 1 && !marked[i][j]) {
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(i * n + j);
int count = 0;
marked[i][j] = true;
while(!linkedList.isEmpty()) {
int node = linkedList.removeFirst();
count++;
int nodeX = node / n;
int nodeY = node % n;
for(int k = 0; k < 4; k++) {
int newX = nodeX + dx[k];
int newY = nodeY + dy[k];
if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1 && !marked[newX][newY]) {
linkedList.add(newX * n + newY);
marked[newX][newY] = true;
}
}
}
max = Math.max(max, count);
}
}
}
return max;
}
}