Skip to content

79. Word Search

Array String Backtracking Depth-First Search Matrix

Medium

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?

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])

        def dfs(i: int, j: int, k: int) -> bool:
            if k == len(word) - 1:
                return board[i][j] == word[k]
            if board[i][j] != word[k]:
                return False

            char = board[i][j]
            board[i][j] = "0"

            for val1, val2 in pairwise((-1, 0, 1, 0, -1)):
                x, y = i + val1, j + val2
                good = 0 <= x < m and 0 <= y < n and board[x][y] != "0"
                if good and dfs(x, y, k + 1):
                    return True

            board[i][j] = char
            return False

        return any(dfs(i, j, 0) for i in range(m) for j in range(n))

Submission Stats:

  • Runtime: 5104 ms (23.85%)
  • Memory: 17.8 MB (87.82%)