经常出的一种类型,
首先判断grid[i][j] == '1'
,
当然这要符合0 <= i < len(grid) and 0 <= j < len(grid[i])
满足条件则令其为零grid[i][j] = '0'
然后对其上下左右元素进行递归
map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))
这样保证所有上下左右有相连的元素只会被计数一次,
最后进行sum()
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def sink(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and grid[i][j] == '1':
grid[i][j] = '0'
map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))
return 1
return 0
return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[i])))