Description

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.

Idea

Backtracking

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        n, m = len(board), len(board[0])
        directions = [[0,1],[0,-1],[1,0],[-1,0]]
        def backtrack(idx, used, i, j):
            if idx == len(word):
                return True
            for dx, dy in directions:
                x, y = i + dx, j + dy
                if (x, y) in used or not (0 <= x < n and 0 <= y < m) or board[x][y] != word[idx]:
                    continue
                used.add((x, y))
                if backtrack(idx+1, used, x, y):
                    return True
                used.remove((x, y))
 
        for i in range(n):
            for j in range(m):
                if board[i][j] == word[0]:
                    if backtrack(1, {(i,j)}, i, j):
                        return True
        return False