Leetcode练习(Python):数组类:第79题:给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

题目:

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

思路:

深度优先和回溯法结合

程序1:

class Solution(object):
    
    directs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    
    def exist(self, board: List[List[str]], word: str) -> bool:
        row = len(board)
        if row == 0:
            return False
        column = len(board[0])
        visited = [[0 for _ in range(column)] for _ in range(row)]          
        for index1 in range(len(board)):
            for index2 in range(len(board[0])):
                if board[index1][index2] == word[0]:
                    visited[index1][index2] = 1
                    if self.backtrack(index1, index2, visited, board, word[1:]) == True:
                        return True
                    else:
                        visited[index1][index2] = 0
        return False     
    def backtrack(self, i, j, visited, board, word):
        if len(word) == 0:
            return True
        for direct in self.directs:
            cur_i = i + direct[0]
            cur_j = j + direct[1]
            if cur_i >= 0 and cur_i < len(board) and cur_j >= 0 and cur_j < len(board[0]) and board[cur_i][cur_j] == word[0]:
                if visited[cur_i][cur_j] == 1:
                    continue
                visited[cur_i][cur_j] = 1
                if self.backtrack(cur_i, cur_j, visited, board, word[1:]) == True:
                    return True
                else:
                    visited[cur_i][cur_j] = 0
        return False
程序2:代码更简洁
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        for index1 in range(len(board)):
            for index2 in range(len(board[0])):
                if self.dfs(board, index1, index2, word)  == True:
                    return True
        return False
    
    
    def dfs(self, board, i, j, word):
        if len(word) == 0:  
            return True
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]:
            return False
        tmp = board[i][j]
        board[i][j] = '0'
        if self.dfs(board, i + 1, j, word[1:]) or self.dfs(board, i - 1, j, word[1:]) \
    or self.dfs(board, i, j + 1, word[1:]) or self.dfs(board, i, j - 1, word[1:]) == True:
            return True
        board[i][j] = tmp
        return False
posted on 2020-04-23 15:03  桌子哥  阅读(1858)  评论(0编辑  收藏  举报