給定一個由 ‘1’(陸地)和 ‘0’(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。
示例 1:
輸入:
11110
11010
11000
00000
輸出: 1
示例 2:
輸入:
11000
11000
00100
00011
輸出: 3
對每一個爲1的位置四個方向搜索,注意將搜過的地方置爲0:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
res, self.x, self.y = 0, len(grid), len(grid[0])
for i in range(self.x):
for j in range(self.y):
if grid[i][j] == '1': # 置爲0
res += 1
grid[i][j] = '0'
self.helper(grid, i, j)
return res
def helper(self, grid, a, b): # 上下左右
for x,y in [(a-1, b), (a+1, b), (a, b-1), (a, b+1)]:
if 0<=x<self.x and 0<=y<self.y and grid[x][y]=='1':
grid[x][y] = '0'
self.helper(grid, x, y)