练习题
基础题
130. 被围绕的区域(Medium)
搜索一圈边上的区域,记录所有与边界相连的 O ,所有内部的 O 都填充为 X
样例
X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
代码
def dfs(i, j, visited, board):
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]:
return
if board[i][j] != "O":
return
visited[i][j] = 1
dfs(i + 1, j, visited, board)
dfs(i - 1, j, visited, board)
dfs(i, j + 1, visited, board)
dfs(i, j - 1, visited, board)
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board: return
n, m = len(board), len(board[0])
visited = [[0] * m for _ in range(n)]
# 搜索周围一圈
for i in range(m):
dfs(0, i, visited, board)
dfs(n - 1, i, visited, board)
for i in range(1, n - 1):
dfs(i, 0, visited, board)
dfs(i, m - 1, visited, board)
for i in range(n):
for j in range(m):
if board[i][j] == 'O' and not visited[i][j]:
board[i][j] = 'X'
257. 二叉树的所有路径(Easy)
使用回溯法
def dfs(root, ans, tmp):
if not root: return
tmp.append(str(root.val))
if not root.left and not root.right:
ans.append('->'.join(tmp))
dfs(root.left, ans, tmp)
dfs(root.right, ans, tmp)
tmp.pop()
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
ans = []
dfs(root, ans, [])
return ans