【LeetCode每天一题】Word Search(搜索单词)

Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
] Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
思路

  在二维矩阵中搜索单词,首先在矩阵中找到word中第一个字符的位置,然后判断该位置是否可以找到word中所有字符,如果没有找到我们继续在矩阵中遍历直到找到下一个与word中首字母相同的单词然后继续判断。如果最后矩阵遍历完毕之后还是没找到,说明矩阵中不存在word。直接返回False。 另外在矩阵中搜寻word单词剩余的部分时,我们需要设置一个辅助矩阵用来记录该位置是否已经搜索过了。
解决代码


 class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
row, cloum = len(board), len(board[0])
tem = [] # 设置辅助矩阵
for i in range(row):
tem.append([0]*cloum) for i in range(row): # 开始遍历查找
for j in range(cloum):
if board[i][j] == word[0]: # 扎到矩阵中与word首字母相等的位置
res = self.find_res(board, word, i, j, 0, tem)
if res:
return res
return False def find_res(self, board, word, row, cloum, index, tem):
if index >= len(word): # 如果index 大于word长度,说明已经遍历完毕,在矩阵中能找到word
return True
if row >= len(board) or cloum >= len(board[0]) or row <0 or cloum < 0 or tem[row][cloum] == 1: # 异常情况
return False tem[row][cloum] = 1
if board[row][cloum] == word[index]: # 四种走法, 上下左右方向都需要判断,中间使用or表示只要有一条路径为True,则结果为True
res = self.find_res(board, word, row+1, cloum, index+1, tem) | self.find_res(board, word, row, cloum+1, index+1, tem) | self.find_res(board, word, row-1, cloum, index+1, tem) | self.find_res(board, word, row, cloum-1, index+1, tem)
if res == True: # 直接返回结果
return True
tem[row][cloum] =0 # 说明没找到,将位置设置会初始状态
return False
上一篇:BZOJ 3675: [Apio2014]序列分割 动态规划 + 斜率优化 + 卡精度


下一篇:在VIM中进行快速的查找和替换