menu

[LeetCode] 079. Word Search *

Problem (Medium)

079. Word Search

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.

Approach 1: Backtracking

Idea

Accepted very short Java solution. No additional space. Python dfs solution with comments.

Solution

    def exist(self, board, word):
        """ 
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        w = list(word)
        width, height = len(board[0]), len(board)
        for r in range(height):
            for c in range(width):
                if self.helper(board, r, c, w, 0): 
                    return True
        return False

    def helper(self, board, r, c, word, i): 
        if i == len(word):
            return True
        if r < 0 or c < 0 or r == len(board) or c == len(board[0]):
            return False
        if board[r][c] != word[i]:
            return False
        board[r][c] = 0 
        exist = self.helper(board, r, c+1, word, i+1) \
             or self.helper(board, r, c-1, word, i+1) \
             or self.helper(board, r+1, c, word, i+1) \
             or self.helper(board, r-1, c, word, i+1)
        board[r][c] = 0 
        return exist

Complexity

  • Time: $O()$
  • Space: $O()$



KF

Comments