LeetCode-剑指 Offer 12. 矩阵中的路径
吐槽自己,赋值号(=)写成了判断号(==),罪了…
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
思路:
- 首先对数组进行循环,目的就是为了找到符合word的第一个值所在位置
- 回溯使用迭代:边界条件、迭代函数、递推公式
- 边界条件:len(word) == length,当length长度到达word长度时,跳出。因为这时length表示要找的下一个元素下标,length是从0开始,所以当length长度到达word长度时,跳出
- 迭代函数:def existcore(self, board, row, col, rows, cols, word, path, length):
- 递推公式:
if self.existcore(board, row, col-1, rows, cols, word, path, length) or self.existcore(board, row-1, col, rows, cols, word, path, length) or self.existcore(board, row, col+1, rows, cols, word, path, length) or self.existcore(board, row+1, col, rows, cols, word, path, length): haspath = True
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if board == None or word == "":
return False
path = [[False]*len(b) for b in board]
rows, cols = len(board), len(board[0])
length = 0
for row in range(rows):
for col in range(cols):
# 找到正确的第一个值开始的序列
if self.existcore(board, row, col, rows, cols, word, path, length):
return True
return False
def existcore(self, board, row, col, rows, cols, word, path, length):
if len(word) == length:
return True
haspath = False
if row >= 0 and row < rows and col >= 0 and col < cols and board[row][col] == word[length] and not path[row][col]:
length += 1
path[row][col] = True
if self.existcore(board, row, col-1, rows, cols, word, path, length) or self.existcore(board, row-1, col, rows, cols, word, path, length) or self.existcore(board, row, col+1, rows, cols, word, path, length) or self.existcore(board, row+1, col, rows, cols, word, path, length):
haspath = True
if not haspath:
length -= 1
path[row][col] = False
return haspath
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix