Leetcode刷题记录——剑指 Offer 12. 矩阵中的路径

Leetcode刷题记录——剑指 Offer 12. 矩阵中的路径_第1张图片

class Solution:
    def __init__(self):
        self.history = set()
    def exist(self, board: List[List[str]], word: str) -> bool:
        if board == [] or board[0] == []:
            return False
        m = len(board)
        n = len(board[0])
        for i in range(m):
            for j in range(n):
                #if board[i][j] == word[0] and len(word):
                history = set()
                if self.search(board,i,j,0,m,n,word,history):
                    return True
        return False


    def search(self,board,i,j,index,m,n,word,history):
        #direction = 0
        #1:上一次是从左到右 这次不i-1

        if i < 0 or j < 0 or i >= m or j >= n or (i,j) in history:
            return False
        
        if board[i][j] != word[index]:
            return False
        history.add((i,j))
        index += 1
        if index == len(word):
            return True
        #index表征目前识别正确的索引
        h1 = history.copy()
        h2 = history.copy()
        h3 = history.copy()
        h4 = history.copy()
        return True if (i-1,j) not in history and (self.search(board,i-1,j,index,m,n,word,h1)) or (i+1,j) not in history and (self.search(board,i+1,j,index,m,n,word,h2)) or (i,j-1) not in history and self.search(board,i,j-1,index,m,n,word,h3) or (i,j+1) not in history and (self.search(board,i,j+1,index,m,n,word,h4)) else False

你可能感兴趣的:(leetcode,python编程技巧)