LeetCode 79. 单词搜索

给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。
同一个单元格内的字母不允许被重复使用。

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

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

提示:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3

class Solution:
    def exist(self, board, word) -> bool:
        def check(board,marked,i,j,word,w_i):
            if i<0 or i >= len(board) or j<0 or j >= len(board[0]) :
                return False
            if marked[i][j] is False:
                return False
            if board[i][j]!=word[w_i] :
                return False
            if w_i==len(word)-1:
                return True
            marked[i][j] = False
            result = check(board,marked,i-1,j,word,w_i+1) or check(board,marked,i+1,j,word,w_i+1) or check(board,marked,i,j-1,word,w_i+1) or check(board,marked,i,j+1,word,w_i+1)
            marked[i][j] = True
            return result

        n = len(board)
        m = len(board[0])
        marked = [[True for _ in range(m)] for _ in range(n)]
        for i in range(n):
            for j in range(m):
                result = check(board,marked,i,j,word,0)
                if result is True:
                    return True
        return False

你可能感兴趣的:(LeetCode 79. 单词搜索)