SDE & MLE Prep

79. Word Search

Problem

Decide whether word can be traced on the letter grid board through horizontally or vertically adjacent cells, using each cell at most once.

Example: board = ["ABCE","SFCS","ADEE"]: "ABCCED" → true; "ABCB" → false

Constraints: board up to 6 × 6; word length ≤ 15. Follow-up: prune the search.

DFS from every cell matching word[0]; mark the cell visited (overwrite with #) while it's on the path, restore on return.

Complexity: O(R·C·3^L).

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        R, C = len(board), len(board[0])

        def dfs(r, c, i):
            if i == len(word):
                return True
            if not (0 <= r < R and 0 <= c < C) or board[r][c] != word[i]:
                return False
            board[r][c] = "#"
            found = dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)
            board[r][c] = word[i]
            return found

        return any(dfs(r, c, 0) for r in range(R) for c in range(C))