题目
思路
遍历每一个网格,若网格为1,岛屿数量+1,利用一个深度优先搜索函数将岛屿置零,注意判断数组边界
代码
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
self.grid = grid
self.result = 0
self.height = len(grid)
self.width = len(grid[0])
self.directions = [[-1,0],[1,0],[0,-1],[0,1]]
for i in range(self.height):
for j in range(self.width):
if self.grid[i][j]=='1':
self.result += 1
self.clean(i,j)
return self.result
def clean(self,i,j):
if self.grid[i][j]=='1': # 终止前置条件
self.grid[i][j]='0'
else: # 终止前置条件
return 0
for direction in self.directions:
temp_h = i+direction[0]
temp_w = j+direction[1]
if temp_h>=0 and temp_h<self.height and temp_w>=0 and temp_w<self.width:
self.clean(temp_h,temp_w)