【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

 

转载于:https://www.cnblogs.com/GoodRnne/p/10792773.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值