Skip to the content.

leetcode [79] 单词搜索


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.

思路:递归收缩,上下左右,记录访问的情况,如果成功即成功,否则,撤销访问。

class Solution:
    def existCore(self, board, word, record, i, j):
        if len(word) == 0:
            return True

        dirs = [[i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]]
        for i in range(4):
            m, n = dirs[i]
            if 0 <= m < len(board) and 0 <= n < len(board[0]) and board[m][n] == word[0] and not record[m][n]:
                record[m][n] = True
                if self.existCore(board, word[1:], record, m, n):
                    return True
                record[m][n] = False
        return False

    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(word) == 0:
            return True
        if len(board) == 0 or len(board[0]) == 0 or len(word) > len(board) * len(board[0]):
            return False
        record = [[False] * len(board[0]) for i in range(len(board))]
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == word[0]:
                    record[i][j] = True
                    if self.existCore(board, word[1:], record, i, j):
                        return True
                    record[i][j] = False

        return False