695. 岛屿的最大面积
695. 岛屿的最大面积 - 力扣(LeetCode) (leetcode-cn.com)
思路:
1.从第一个格子开始,如果当中元素为1,则开始广度或者深度搜索
2.每次搜索过的格子内的值更改为0或其他数字,防止反复搜索,并记录每次搜索的值
3.取多次搜索的最大值作为答案返回即可
代码:
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
que = collections.deque()
ans = 0
area = 0
for x, i in enumerate(grid):
for y, j in enumerate(i):
if grid[x][y]: # 这里好像不能用j为什么?
que.append((x, y))
grid[x][y] = 0
area = 1
while que:
x, y = que.popleft()
for mx, ny in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
if 0 <= mx < m and 0 <= ny < n and grid[mx][ny] == 1:
area += 1
que.append((mx, ny))
grid[mx][ny] = 0
ans = max(ans, area)
return ans
顺便记录下第一次两个复杂度排名都比较靠前
问题:
为何grid[x][y] 更改为j后会导致测试用例[[1,0,1],[1,0,0],[0,0,1]]输出结果为3,并且会把grid[1][2]当作一个1?
以上
坚持 共勉