class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
nextStep = [[0, 1], [0, -1], [-1, 0], [1, 0]]
step = 0
def dfs(grid, x, y):
if x < 0 or y < 0 or x > len(grid) - 1 or y > len(grid[0]) - 1 or grid[x][y] != "1":
return
grid[x][y] = "0"
for i in range(len(nextStep)):
dfs(grid, x + nextStep[i][0], y + nextStep[i][1])
res = 0
for i in range(len(grid)): #遍历行
for j in range(len(grid[0])):#b遍历列
if grid[i][j] == "1":
dfs(grid, i, j)
step += 1
return step
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
nex = [[0, 1], [0, -1], [1, 0], [-1, 0]]
m = len(grid)
n = len(grid[0])
cnt = 0
def dfs(x, y):
if x < 0 or x >= m or y < 0 or y >= n or grid[x][y] != '1':
return
grid[x][y] = '0'
for i in range(len(nex)):
dfs(x + nex[i][0], y + nex[i][1])
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i,j)
cnt += 1
return cnt
130. 被围绕的区域
class Solution:
def solve(self, board: List[List[str]]) -> None:
if not board:
return []
nex = [[0, 1], [0, -1], [-1, 0], [1, 0]]
m = len(board)
n = len(board[0])
def dfs(x, y):
if x < 0 or x >= m or y < 0 or y >= n or board[x][y] != 'O':
return
board[x][y] = '-'
for i in range(len(nex)):
dfs(x + nex[i][0], y + nex[i][1])
for i in range(n):
dfs(0, i)
dfs(m -1, i)
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '-':
board[i][j] = 'O'
return board
695. 岛屿的最大面积
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
nex = [[0, 1], [0, -1], [1, 0], [-1, 0]]
m = len(grid)
n = len(grid[0])
ret = []
self.cnt = 0
def dfs(x, y):
if x < 0 or x >= m or y < 0 or y >= n or grid[x][y] != 1:
return
grid[x][y] = 0
self.cnt += 1
for i in range(len(nex)):
dfs(x + nex[i][0], y + nex[i][1])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
dfs(i,j)
ret.append(self.cnt)
self.cnt = 0
if ret:
return max(ret)
return 0