Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.2 kB
1
Indexable
Never
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        
        
        def recur(i, j, index):
            
            if index == len(word):
                return True
            
            if min(i,j) < 0 or i >= n or j >= m or board[index] != board[i][j]:
                return False
            
            # exit if it already exists in the current path
            if (i, j) in path:
                return False
            
            path.add((i, j))
            
            if recur(i-1, j, index + 1) or recur(i+1, j, index +1) or \
                recur(i, j-1, index+1) or recur(i, j+1, index+1):
                return True
            
            path = set()
            
            return False
         
        path = set() # Using a set since you can not use a 
        n, m = len(board), len(board[0])
        
        for p in range(len(board)):
            for q in range(len(board[0])):        
                if recur(p, q, 0):
                    return True
                
        return False