【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单词剩余的部分时,我们需要设置一个辅助矩阵用来记录该位置是否已经搜索过了。
解决代码


 1 class Solution(object):
 2     def exist(self, board, word):
 3         """
 4         :type board: List[List[str]]
 5         :type word: str
 6         :rtype: bool
 7         """
 8         row, cloum = len(board), len(board[0])
 9         tem = []         # 设置辅助矩阵
10         for i in range(row):
11             tem.append([0]*cloum)
12             
13         for i in range(row):      # 开始遍历查找
14             for j in range(cloum):
15                 if board[i][j] == word[0]:   # 扎到矩阵中与word首字母相等的位置
16                     res = self.find_res(board, word, i, j, 0, tem)
17                     if res:
18                         return res
19         return False
20             
21         
22     def find_res(self, board, word, row, cloum, index, tem):
23         if index >= len(word):         # 如果index 大于word长度,说明已经遍历完毕,在矩阵中能找到word
24             return True
25         if row >= len(board) or cloum >= len(board[0]) or row <0 or cloum < 0 or tem[row][cloum] == 1:   # 异常情况
26             return False
27 
28         tem[row][cloum] = 1         
29         if board[row][cloum] == word[index]:    # 四种走法, 上下左右方向都需要判断,中间使用or表示只要有一条路径为True,则结果为True
30             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)
31             if res == True:  #  直接返回结果
32                 return True
33         tem[row][cloum] =0   # 说明没找到,将位置设置会初始状态
34         return False

 

posted @ 2019-04-29 20:43  GoodRnne  阅读(734)  评论(0编辑  收藏  举报