岛屿的个数
leetcode 200. 岛屿的个数: https://leetcode-cn.com/problems/number-of-islands/
思路: DFS,走过一个要改成-1。
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if len(grid) == 0:
return 0
m = len(grid)
n = len(grid[0])
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
res += 1
self.dfs(grid, i, j)
return res
def dfs(self,grid,i,j):
grid[i][j] = '-1'
orients = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for o in orients:
p = i + o[0]
q = j + o[1]
if p >= 0 and q >= 0 and p < len(grid) and q < len(grid[0]) and grid[p][q] == '1':
self.dfs(grid, p, q)
return
岛屿最大面积(最大连通子图)
leetcode 695 岛屿最大面积:https://leetcode-cn.com/problems/max-area-of-island/submissions/
class Solution:
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if len(grid) == 0:
return 0
m = len(grid)
n = len(grid[0])
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
area = self.dfs(grid, i, j)
res = max(res, area)
return res
def dfs(self, grid, i, j):
area = 1
grid[i][j] = -1 #表示已经走过
orients = [[-1,0],[1,0],[0,-1],[0,1]]
for o