經(jīng)常出的一種類型,
首先判斷grid[i][j] == '1'
,
當(dāng)然這要符合0 <= i < len(grid) and 0 <= j < len(grid[i])
滿足條件則令其為零grid[i][j] = '0'
然后對其上下左右元素進(jìn)行遞歸
map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))
這樣保證所有上下左右有相連的元素只會被計(jì)數(shù)一次,
最后進(jìn)行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])))