👨‍💻 738LeetCode

Word Search

Question

Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where adjacent cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Solution

Backtracking. Classic DFS.

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def is_in_border(x, y):
            return True if 0 <= x and x < len(board) \
                   and 0 <= y and y < len(board[0]) else False


        def dfs(x, y, word):
            if len(word) == 0:
                return True
            if not is_in_border(x, y):
                return False
            if board[x][y] != word[0]:
                return False
            dummy, board[x][y] = board[x][y], ' '
            flag = dfs(x + 1, y, word[1:]) or \
                   dfs(x - 1, y, word[1:]) or \
                   dfs(x, y + 1, word[1:]) or \
                   dfs(x, y - 1, word[1:])
            board[x][y] = dummy
            return flag


        for x in range(len(board)):
            for y in range(len(board[0])):
                if dfs(x, y, word):
                    return True
        return False