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.

Example 1:

  • Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED”
  • Output: true

Example 2:

  • Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “SEE”
  • Output: true

Example 3:

  • Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCB”
  • Output: false

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

Submitted Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def backtrack(r, c, i):
            if board[r][c] != word[i]:    # 불일치
                return False
            if i == len(word) - 1:        # word를 마지막까지 완성
                return True
            temp = board[r][c]
            board[r][c] = "#"             # 방문한 셀 표시
            is_next = (
                (r > 0 and backtrack(r-1, c, i+1)) or
                (r < rows-1 and backtrack(r+1, c, i+1)) or
                (c > 0 and backtrack(r, c-1, i+1)) or
                (c < cols-1 and backtrack(r, c+1, i+1))
            )
            board[r][c] = temp            # 방문 표시 되돌리기
            return is_next

        rows, cols = len(board), len(board[0])
        for r in range(rows):
            for c in range(cols):
                if board[r][c] == word[0] and backtrack(r, c, 0): # word 시작점 찾고 재귀호출
                    return True

Runtime: 2553 ms | Beats 91.11%
Memory: 19.63 MB | Beats 8.41%

먼저 board를 돌면서 word의 시작 문자가 있는지 확인한다. 있다면 이후 4방향으로 재귀 호출을 시도해서 끝까지 word를 이을 수 있는지 확인하면 된다. 이미 방문한 셀은 임시로 #으로 표시해서 다시 방문하지 않기 때문에 사실 첫 번째 문자 이후로는 최대 3방향으로 나아간다.

board = [[A,B], [B,C]]
word = “ABD”

                     A B
                     B C
backtrack(0,0,0)          # B 
                          B C 
  backtrack(0,1,1)             # #
                               B C
    backtrack(1,1,2)      # B  ← false
                          B C  
  backtrack(1,0,1)             # B
                               # C
    backtrack(1,1,2)      # B  ← false
                          B C
                     A B  ← false
                     B C 

return False

Other Solutions

1st

class Solution:
    def exist(self, board, word):
        def backtrack(i, j, k):
            if k == len(word):
                return True
            if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[k]:
                return False
            
            temp = board[i][j]
            board[i][j] = ''
            
            if backtrack(i+1, j, k+1) or 
               backtrack(i-1, j, k+1) or 
               backtrack(i, j+1, k+1) or 
               backtrack(i, j-1, k+1):
                return True
            
            board[i][j] = temp
            return False
        
        for i in range(len(board)):
            for j in range(len(board[0])):
                if backtrack(i, j, 0):
                    return True
        return False

time complexity: 𝑂(𝑚*𝑛*3𝓁) ← l=len(word)
space complexity: 𝑂(𝓁)

Leave a comment