leetcode79 -- Word Search (重要)

leetcode79 -- 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.


这种类型的题一般都是用DFS来做的,如下

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board)==0 or len(board[0])==0:
            return False
        
        m, n = len(board), len(board[0])
        visited = [[False for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if self.search(board, word, 0, i, j, visited):
                    return True
        return False
        
        
    def search(self, board, word, idx, i, j, visited):
        if idx==len(word):
            return True
        m,n = len(board),len(board[0])
        
        if i<0 or j<0 or i>=m or j>=n or visited[i][j] or board[i][j] != word[idx]:
            return False
        
        visited[i][j]=True
        res =any([self.search(board, word, idx+1, i-1,j,visited), self.search(board, word, idx+1, i+1,j, visited),
                    self.search(board, word, idx+1,i,j-1, visited), 
                        self.search(board, word, idx+1, i, j+1, visited)])
                    
        visited[i][j] = False
        return res

也可以不用visited数组来标记

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board)==0 or len(board[0])==0:
            return False
        
        m, n = len(board), len(board[0])
        # visited = [[False for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if self.search(board, word, 0, i, j):
                    return True
        return False
               
    def search(self, board, word, idx, i, j):
        if idx==len(word):
            return True
        m,n = len(board),len(board[0])
        
        if i<0 or j<0 or i>=m or j>=n or board[i][j] != word[idx]:
            return False
        
        # visited[i][j]=True
        temp = board[i][j]
        board[i][j] = '#'
        res =any([self.search(board, word, idx+1, i-1,j), self.search(board, word, idx+1, i+1,j),
                    self.search(board, word, idx+1,i,j-1), 
                        self.search(board, word, idx+1, i, j+1)])          
        # visited[i][j] = False
        board[i][j] = temp
        return res

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦