79. Word Search(Python3)

79. Word Search(Python3)

题目

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.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.

解题方案

思路:

  • dfs题目,稍微复杂一些
  • 首先要循环找到开头的字母,才能进行dfs
  • 其次是dfs要依次判断上下左右,以及对边界和曾经使用过的字母做处理,做处理之后回到上一层还要做还原

代码:

class Solution:
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        def dfs(index,row,col):
            if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]):
                return False
            if word[index] == board[row][col]:
                board[row][col] = '#'
                if index == len(word)-1 or \
                    dfs(index+1,row+1,col) or \
                    dfs(index+1,row-1,col) or \
                    dfs(index+1,row,col+1) or \
                    dfs(index+1,row,col-1) :
                    return True
                board[row][col] = word[index]
            return False

        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == word[0]:
                    if dfs(0,i,j):
                        return True
        return False

你可能感兴趣的:(leetcode)