695. Max Area of Island
Medium
6048149Add to ListShare
You are given an m x n
binary matrix grid
. 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.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
Example 1:
Input: grid = [[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]] Output: 6 Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]] Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
or1
.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""
assert Solution().maxAreaOfIsland([[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
assert Solution().maxAreaOfIsland([[0, 0, 0, 0, 0, 0, 0, 0]]) == 0
assert Solution().maxAreaOfIsland([[0, 0, 0, 0, 0, 0, 0, 1]]) == 1
assert Solution().maxAreaOfIsland([[1, 1, 0, 0, 0, 0, 0, 1]]) == 2
assert Solution().maxAreaOfIsland([[1]]) == 1
解题思路:深搜四个方向遍历标记
时间复杂度:O(nm) 空间复杂度:O(1)
"""
maxArea, n, m = 0, len(grid), len(grid[0])
d = [[0, 1], [1, 0], [-1, 0], [0, -1]]
# 深搜遍历
def dfs(x: int, y: int) -> int:
if grid[x][y] == 0:
return 0
grid[x][y] = 0
area = 1
for i in range(len(d)):
nextX = x + d[i][0]
nextY = y + d[i][1]
if nextX >= n or nextY >= m or nextX < 0 or nextY < 0:
continue
area += dfs(nextX, nextY)
return area
for i in range(n):
for j in range(m):
maxArea = max(maxArea, dfs(i, j))
return maxArea