99.岛屿数量 深搜
class Solution:def numIslands(self, grid: List[List[str]]) -> int:def dfs(i, j):if not 0 <= i < m or not 0 <= j < n or grid[i][j] == "0":returngrid[i][j] = "0"for x,y in (i+1,j),(i-1,j),(i,j+1),(i,j-1):dfs(x,y)m, n = len(grid), len(grid[0])ans = 0for i in range(m):for j in range(n):if grid[i][j] == "1":dfs(i, j)ans += 1return ans
99.岛屿数量 广搜
class Solution:def numIslands(self, grid: List[List[str]]) -> int:# 深度优先搜索:def bfs(i, j):queue = [(i, j)]grid[i][j] = "0"while queue:x, y = queue.pop(0)for a, b in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:if a>=0 and a<n and b>=0 and b<m and grid[a][b]=="1":queue.append((a, b))grid[a][b] = "0"n, m = len(grid), len(grid[0])res = 0for i in range(n):for j in range(m):if grid[i][j] == "1":res += 1bfs(i, j)return res
100.岛屿的最大面积
class Solution:def maxAreaOfIsland(self, grid: List[List[int]]) -> int:if not grid: return 0l, w = len(grid), len(grid[0])maxarea = 0def dfs1(i, j):if i<0 or i>=l or j>=w or j<0 or grid[i][j]==0: return 0grid[i][j] = 0return 1 + dfs1(i+1, j) + dfs1(i-1,j) + dfs1(i,j+1) + dfs1(i, j-1)for i in range(l):for j in range(w):if grid[i][j]:maxarea = max(maxarea, dfs1(i,j))return maxarea