代码改变世界

[LeetCode] 79. Word Search_Medium tag: Backtracking, DFS

2021-07-28 11:04  Johnson_强生仔仔  阅读(42)  评论(0编辑  收藏  举报

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?

 

Ideas:

For each cell, try to recursively checking whether we should continue. And backtrack if one direction does not work. If one of the direction is True, then return True. Otherwise wait until every direction return False, then return False.

 

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        for i in range(m):
            for j in range(n):
                if self.helper(board, i, j, 0, word):
                    return True
        return False
    
    def helper(self, board, i, j, pos, word):
        if pos == len(word):
            return True
        if 0 <= i < len(board) and 0 <= j < len(board[0]):
            char = board[i][j]
            if char == word[pos]:
                board[i][j] = '#'
                for d1, d2 in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    if self.helper(board, i + d1, j + d2, pos + 1, word):
                        return True
                board[i][j] = char

return False