两个错误的点:
1.误解题意:题目传进来的不一定是正方形,可能是长方形,所以grid的长度和每行的长度不一致
2.covered函数中如果这个点已经是0就不必再遍历周围的值,也就是它是岛屿的边,遇到边就停
def numIslands(grid):
def covered(i: object, j: object) -> object:
nonlocal grid, l,k
if grid[i][j] == '0':
return
grid[i][j] = '0'
if -1 < i - 1 < l and -1 < j < k and grid[i - 1][j] == '1':
covered(i - 1, j)
if -1 < i + 1 < l and -1 < j < k and grid[i + 1][j] == '1':
covered(i + 1, j)
if -1 < i < l and -1 < j - 1 < k and grid[i][j - 1] == '1':
covered(i, j - 1)
if -1 < i < l and -1 < j + 1 < k and grid[i][j + 1] == '1':
covered(i, j + 1)
l = len(grid)
k = len(grid[0])
count = 0
for i in range(l):
for j in range(k):
if grid[i][j] == '1':
print(f'{i}-{j}')
count += 1
covered(i, j)
continue
return count
grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
···