LeetCode代码
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
area = 0
temp_area = 0
m = len(grid)
n = len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
unvisited = set()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
unvisited.add((i, j))
grid[i][j] = 0
temp_area = 1
while unvisited:
ix, iy = unvisited.pop()
for dx, dy in directions:
if 0 <= ix + dx < m and 0 <= iy + dy < n and grid[ix + dx][iy + dy] == 1:
unvisited.add((ix + dx, iy + dy))
grid[ix + dx][iy + dy] = 0
temp_area += 1
if area < temp_area:
area = temp_area
return area
运行结果如下,可以看出,速度还有很大的提升空间
pycharm代码
class Solution:
def maxAreaOfIsland(self, grid):
area = 0
temp_area = 0
m = len(grid)
n = len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
unvisited = set()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
unvisited.add((i, j))
grid[i][j] = 0
temp_area = 1
while unvisited:
ix, iy = unvisited.pop()
for dx, dy in directions:
if 0 <= ix + dx < m and 0 <= iy + dy < n and grid[ix + dx][iy + dy] == 1:
unvisited.add((ix + dx, iy + dy))
grid[ix + dx][iy + dy] = 0
temp_area += 1
if area < temp_area:
area = temp_area
return area
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]]
print(Solution().maxAreaOfIsland(grid))
grid = [[0, 0, 0, 0, 0, 0, 0, 0]]
print(Solution().maxAreaOfIsland(grid))
看了看大佬的递归写法,很有参考意义
class Solution(object):
def maxAreaOfIsland(self, grid):
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return (1 + area(r+1, c) + area(r-1, c) +
area(r, c-1) + area(r, c+1))
return max(area(r, c)
for r in range(len(grid))
for c in range(len(grid[0])))