classSolution: defmaxAreaOfIsland(self, grid: List[List[int]]) -> int: maxArea = 0 m, n = len(grid), len(grid[0])
for i, l inenumerate(grid): for j, s inenumerate(l): if grid[i][j]: maxArea = max(self.dfs(grid, i, j), maxArea) return maxArea
defdfs(self, grid, m, n): if grid[m][n] == 0: return0 area = 1 grid[m][n] = 0 for i, j in [[0, 1], [0, -1], [-1, 0], [1, 0]]: a = m + i b = n + j if a >= 0and b >= 0and a < len(grid) and b < len(grid[0]): area += self.dfs(grid, a, b) return area
547、省份数量
一样使用深度优先搜索
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: deffindCircleNum(self, isConnected: List[List[int]]) -> int: defdfs(x): for i inrange(len(isConnected)): if isConnected[x][i] == 1and i notin visited: visited.add(i) dfs(i)
n = len(isConnected) visited = set() ans = 0 for i inrange(n): if i notin visited: dfs(i) ans += 1
classSolution: defpacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: m, n = len(heights), len(heights[0])
defsearch(ocean): res = set()
defdfs(x, y): if (x, y) notin res: res.add((x, y)) for i, j in [[0, 1], [0, -1], [-1, 0], [1, 0]]: a = x + i b = y + j if a >= 0and b >= 0and a < m and b < n and heights[a][b] >= heights[x][y]: dfs(a, b)
for (i, j) in ocean: dfs(i, j) return res
pacificOcean = [(0, i) for i inrange(n)] + [(i, 0) for i inrange(m)] atlanticOcean = [(i, n - 1) for i inrange(m)] + [(m - 1, i) for i inrange(n)]