79. Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.


def exist(self, board: List[List[str]], word: str) -> bool:
                       
    def dfs(r, c, w):
        if w == W:
            return True
       
        t = board[r][c]
        board[r][c] = '#'            
       
        nextCells = [(r+dr, c+dc) for (dr, dc) in dirs]
        for ni, nj in nextCells:
            if ni >=0 and ni < R and nj >=0 and nj < C:
                    if board[ni][nj] == word[w]:                                                        
                        if dfs(ni, nj, w+1):                            
                            return True
                       
        board[r][c] = t
        return False
       
   
    dirs = [(0,1), (1,0), (0,-1), (-1,0)]
    R, C = len(board), len(board[0])
    W = len(word)
   
    for r in range(R):
        for c in range(C):
            if board[r][c] != word[0]:
                continue
            if W == 1:
                return True        
            if dfs(r,c,1):            
                return True
                           
    return False

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break