leetcode刷题-79单词搜索

题目

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

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

 

示例:

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

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

思路

使用深度遍历搜索:每次都对一个点深度遍历,利用marked二维数组来确定当前节点是否可以访问

实现

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        self.row_len = len(board)
        if self.row_len == 0:
            return False
        self.col_len = len(board[0])
        self.marked = [[False for i in range(self.col_len)] for i in range(self.row_len)]
        self.directions = [(0, -1), (-1, 0), (0, 1), (1, 0)]
        for i in range(self.row_len):
            for j in range(self.col_len):
                if self.__dfs(board, word, 0 ,i ,j):
                    return True
        return False

    def __dfs(self, board, word, index, row_index, col_index):
        if index == len(word) -1:
            return board[row_index][col_index] == word[index]
        if board[row_index][col_index] == word[index]:
            self.marked[row_index][col_index] = True
            for direction in self.directions:
                new_row_index = row_index + direction[0]
                new_col_index = col_index + direction[1]
                if 0 <= new_row_index < self.row_len and \
                   0 <= new_col_index < self.col_len and \
                   self.marked[new_row_index][new_col_index] is False and \
                   self.__dfs(board, word, index+1, new_row_index, new_col_index):
                   return True
            self.marked[row_index][col_index] = False
        return False

 

posted @ 2020-08-11 10:48  maoguai  阅读(107)  评论(0编辑  收藏  举报