欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

79. Word Search

程序员文章站 2022-07-14 17:30:57
...

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

class Solution(object):
    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