algo/leetcode

79. Word Search

sourmc 2025. 2. 27. 23:05

79. Word Search

 

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.

Solution

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        N = len(board)
        M = len(board[0])
        ans = False
        # 동/남/서/북
        d = [[0, 1], [1, 0], [0, -1], [-1, 0]]

        def dfs(x: int, y: int, s: str):
            nonlocal ans
            if s == word:
                ans = True
            if ans:
                return

            tmp = board[x][y]
            board[x][y] = ''

            for i in range(4):
                nx = x + d[i][0]
                ny = y + d[i][1]
                if nx < 0 or nx >= N or ny < 0 or ny >= M:
                    continue
                if board[nx][ny] and word.startswith(s + board[nx][ny]):
                    dfs(nx, ny, s + board[nx][ny])
            board[x][y] = tmp

        for i in range(N):
            for j in range(M):
                if board[i][j] == word[0]:
                    dfs(i, j, board[i][j])

        return ans

 

 

'algo > leetcode' 카테고리의 다른 글

213. House Robber II  (0) 2025.02.28
39. Combination Sum  (0) 2025.02.18
121. Best Time to Buy and Sell Stock  (0) 2025.02.08
128. Longest Consecutive Sequence  (0) 2025.02.08
306. Additive Number  (0) 2025.01.27