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, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        def dfs(i,j,pos):
            if(i<0 or j<0 or i==len(board) or j==len(board[0])):
                return False
            if pos == len(word):
                return True
            if board[i][j] == word[pos]:
                board[i][j] = None
                temp = dfs(i+1,j,pos+1) or dfs(i-1,j,pos+1) or dfs(i,j+1,pos+1) or dfs(i,j-1,pos+1)
                board[i][j] = word[pos]
                return temp

        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j]==word[0]:
                    if len(word)==1:
                        return True
                    if dfs(i,j,0):
                        return True
        return False
原文地址:https://www.cnblogs.com/bernieloveslife/p/9733243.html