leetcode-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.)

Example 1:

1
2
3
4
5
6
7
8
[[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]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

1
[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

分析


深度优先遍历,每次遇到1开始计数,先将自身置为1,避免无限递归,结束递归的条件是到达矩阵边界或遇到 0。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
int[][] steps = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

public int maxAreaOfIsland(int[][] grid) {
int result = 0;
int row = grid.length;
int column = grid[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (grid[i][j] == 1) {
result = Math.max(result, dfs(grid, i, j, row, column));
}
}
}
return result;
}

private int dfs(int[][] grid, int x, int y, int row, int column) {
if (x < 0 || y < 0 || x >= row || y >= column || grid[x][y] == 0) {
return 0;
}
int count = 1;
grid[x][y] = 0;
for (int[] step: steps) {
count += dfs(grid, x+step[0], y+step[1], row, column);
}
return count;
}
}

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func maxAreaOfIsland(grid [][]int) int {
row := len(grid)
col := len(grid[0])
result := 0
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
now := 0
if grid[i][j] != 0 {
now = dfs(i, j, now, grid)
}
if result < now {
result = now
}
}
}
return result
}

func dfs(i, j, count int, grid [][]int) int {
if i < 0 || j < 0 || i >= len(grid) || j >= len(grid[0]) || grid[i][j] == 0 {
return count
}
grid[i][j] = 0
count += 1
count = dfs(i-1, j, count, grid)
count = dfs(i+1, j, count, grid)
count = dfs(i, j-1, count, grid)
count = dfs(i, j+1, count, grid)
return count
}

相关问题


题目来源