兩個錯誤的點:
1.誤解題意:題目傳進來的不一定是正方形,可能是長方形,所以grid的長度和每行的長度不一致
2.covered函數(shù)中如果這個點已經(jīng)是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"]
]
···