[DFS]79. Word Search

  • 分类:DFS
  • 时间复杂度: O(mn4^l)**
  • 空间复杂度: O(nn+l)*

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

代码:

class Solution:
    def exist(self, board: 'List[List[str]]', word: 'str') -> 'bool':
        if board==None or len(board)==0 or len(board[0])==0:
            return False
        
        m=len(board)
        n=len(board[0])
        isVisited=[[0 for i in range(n)] for i in range(m)]
        for i in range(m):
            for j in range(n):
                if self.dfs(i,j,0,word,board,isVisited):
                    return True
        return False

    def dfs(self,x,y,d,word,board,isVisited):
        if x<0 or x>=len(board) or y<0 or y>=len(board[0]):
            return False
        if isVisited[x][y]:
            return False

        if board[x][y]==word[d]:
            isVisited[x][y]=1
            if d==len(word)-1:
                return True
            if (self.dfs(x+1,y,d+1,word,board,isVisited) or self.dfs(x-1,y,d+1,word,board,isVisited) or self.dfs(x,y+1,d+1,word,board,isVisited) or self.dfs(x,y-1,d+1,word,board,isVisited)):
                return True
            isVisited[x][y]=0
        return False

讨论:

1.和78题差不多
2.if (self.dfs(x+1,y,d+1,word,board,isVisited) or self.dfs(x-1,y,d+1,word,board,isVisited) or self.dfs(x,y+1,d+1,word,board,isVisited) or self.dfs(x,y-1,d+1,word,board,isVisited))这里好难想,想了半天才figure out要这么写,不然之后isVisited不能置零。

你可能感兴趣的:([DFS]79. Word Search)