解题思路-leetcode79题:单词搜索
题目描述:
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
示例 2:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
输出:true
示例 3:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成
进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?
解题思路:本题采用递归的方法,递归函数内根据不同情况选择搜索方向,例如上下左右,用变量t记录上一次搜索方向,用check矩阵记录搜索历史。递归函数外首先遍历矩阵,找到word的首字符,然后从当前位置调用递归函数进行搜索,搜索到结果后,将结果列表res加1,最后判断res的长度,大于0则返回True,否则返回False。代码如下:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
res = []
m = len(board)
l = len(board[0])
check = [[0 for j in range(l)] for i in range(m)]
def search(i, j, n, t):
if n == len(word):
print("111")
res.append(1)
return
if j>0 and t!=0 and board[i][j-1] == word[n] and check[i][j-1] == 0:
t0 = t
t = 2
check[i][j-1] = 1
search(i, j - 1, n + 1, t)
t = t0
check[i][j-1] = 0
if i>0 and t!=1 and board[i-1][j] == word[n] and check[i-1][j] == 0:
t0 = t
t = 3
check[i-1][j] = 1
search(i - 1, j, n + 1, t)
t = t0
check[i-1][j] = 0
if j<l-1 and t!=2 and board[i][j+1] == word[n] and check[i][j+1] == 0:
t0 = t
t = 0
check[i][j+1] = 1
search(i, j + 1, n + 1, t)
t = t0
check[i][j+1] = 0
if i<m-1 and t!=3 and board[i+1][j] == word[n] and check[i+1][j] == 0:
t0 = t
t = 1
check[i+1][j] = 1
search(i + 1, j, n + 1, t)
t = t0
check[i+1][j] = 0
for i in range(m):
for j in range(l):
if board[i][j] == word[0]:
check[i][j] = 1
search(i, j, 1, -1)
check[i][j] = 0
if len(res) != 0:
return True
else:
return False
提交后,通过。