给定一个包含了一些 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]]
对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。
示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。
注意: 给定的矩阵grid 的长度和宽度都不超过 50。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
深度优先+栈(自己的)
#方法一致,但其官方解优化很多
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
dp = [0]
dp_store = []
l_x = len(grid[0])
l_y = len(grid)
def bianli(y,x):
#遍历四周,并拓展
#print('b',y,x)
queue = [[y,x]]
res = 1
def single_bianli(single_y,single_x):
if single_y<l_y and single_y>=0 and single_x>=0 and single_x<l_x and \
grid[single_y][single_x] == 1 and ([single_y,single_x] not in dp_store):
queue.append([single_y,single_x])
dp_store.append([single_y,single_x])
return 1
else:
return 0
while(queue!=[]):
# i代表y方向,j代表x方向
#print(queue)
q0 = queue.pop(0)
i, j = q0[0],q0[1]
res += single_bianli(i+1,j)
res += single_bianli(i,j+1)
res += single_bianli(i-1,j)
res += single_bianli(i,j-1)
dp.append(res)
for i in range(l_y):
for j in range(l_x):
if grid[i][j] == 1 and ([i,j] not in dp_store):
#print('a',i,j)
dp_store.append([i,j])
#遍历周围所有四个方向
bianli(i,j)
return max(dp)
官方题解 (优化很多)
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
ans = 0
for i, l in enumerate(grid):
for j, n in enumerate(l):
cur = 0
stack = [(i, j)]
while stack:
cur_i, cur_j = stack.pop()
if cur_i < 0 or cur_j < 0 or cur_i == len(grid) or cur_j == len(grid[0]) or grid[cur_i][cur_j] != 1:
continue
cur += 1
grid[cur_i][cur_j] = 0
for di, dj in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
next_i, next_j = cur_i + di, cur_j + dj
stack.append((next_i, next_j))
ans = max(ans, cur)
return ans