首页 > 其他 > 详细

79. Word Search

时间:2019-02-10 18:33:21      阅读:171      评论:0      收藏:0      [点我收藏+]

leetcod79题在矩阵中寻找某个单词

"""
79. Word Search
Medium

Share
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.
"""

用深度优先搜索,首先找到首单词,因为矩阵中的单个元素只能用一次所以要记录路径,还要记录当前位置,

class Solution(object):
    def searchWordinBoard(self, board, word, len_word, n, i, j, pathset):
        """
        :type board:list[list[str]]
        :type word:str
        :type n,i,j:int
        :type pathset:set
        :rtype:bool
        几个参数分别代表矩阵,单词,单词长度,当前字母,当前矩阵位置,已经经过的路径集合
        """
        if i<0 or j<0 or i>=len(board) or j>=len(board[0]):
            return False
        if word[n]!=board[i][j] or (i,j) in pathset:
            return False
        if n == len_word-1:
            return True
        pathset.add((i,j))
        result = self.searchWordinBoard(board, word, len_word, n+1, i-1, j, pathset) or             self.searchWordinBoard(board, word, len_word, n+1, i, j-1, pathset) or             self.searchWordinBoard(board, word, len_word, n+1, i+1, j, pathset) or             self.searchWordinBoard(board, word, len_word, n+1, i, j+1, pathset)
        pathset.remove((i,j))
        return result


    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        if word == "":
            return True
        if not board or not board[0]:
            return False
        len_row, len_col = len(board), len(board[0])
        for i in range(len_row):
            for j in range(len_col):
                if word[0] != board[i][j]:
                    continue
                if self.searchWordinBoard(board, word, len(word), 0, i, j, set()):
                    return True
        return False

 

79. Word Search

原文:https://www.cnblogs.com/mangmangbiluo/p/10359894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!