做背景网站优化精灵
leetcode200. 岛屿数量
题目
思路
遍历每一个网格,若网格为1,岛屿数量+1,利用一个深度优先搜索函数将岛屿置零,注意判断数组边界
代码
class Solution:def numIslands(self, grid: List[List[str]]) -> int:self.grid = gridself.result = 0self.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 += 1self.clean(i,j)return self.resultdef clean(self,i,j):if self.grid[i][j]=='1': # 终止前置条件self.grid[i][j]='0'else: # 终止前置条件return 0for 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)