剑指 offer 中二维矩阵搜索相关
题目:剑指offer 12. 二维矩阵中的路径 及 13. 求机器人可达点数
说明: 本文中出现的代码与伪代码均为 Python 代码
DFS(深度优先搜索)+ 剪枝(遇到这条路径不符合则立即返回)
# 12 二维矩阵中的路径
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
len_word = len(word)
row = len(board)
col = len(board[0])
def dfs(i, j, k):
if not 0 <= i < row or not 0 <= j < col or board[i][j] != word[k]: # 可行性剪枝
return False
if k == len_word - 1:
return True
temp, board[i][j] = board[i][j], '-'
res = dfs(i + 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j - 1, k + 1)
board[i][j] = temp
return res
for i in range(row):
for j in range(col):
if dfs(i, j, 0):
return True
return False
# 13. 机器人可达点数
def sum_digtal(num):
ans = 0
while num:
ans += num % 10
num //= 10
return ans
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
visitied = set() # 已访问节点集合
def dfs(i, j):
# 可行性剪枝
if sum_digtal(i) + sum_digtal(j) > k or (i,j) in visitied or i > m - 1 or j > n - 1:
return 0
visitied.add((i, j)) # 标记已访问节点
return 1 + dfs(i + 1, j) + dfs(i, j + 1)
return dfs(0, 0)
BFS(广度优先搜索)Python 解法
广度优先搜索多使用队列实现, Python 中使用 from queue import Qqueue
即可使用队列。下面给出上述两个问题的解法。
13 题代码引用自 leetcode 官方题解
# 13. 机器人可达点数
def digitsum(n):
ans = 0
while n:
ans += n % 10
n //= 10
return ans
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
from queue import Queue
q = Queue()
q.put((0, 0))
s = set()
while not q.empty():
x, y = q.get()
if (x, y) not in s and 0 <= x < m and 0 <= y < n and digitsum(x) + digitsum(y) <= k:
s.add((x, y))
for nx, ny in [(x + 1, y), (x, y + 1)]:
q.put((nx, ny))
return len(s)
对于 DFS 和 BFS 小结
-
DFS 为深度优先搜索,从一个点出发,遍历条一条路径后回溯,然后从另一个点出发,继续遍历一条路径,在实现上为递归方式,剪枝的思想是遇到不符合的点,立即回溯,设置一个不符合条件的判断,发生不符合条件情况则立即
return
即可。 -
BFS 为广度优先搜索算法