zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    分段路由的复兴
    动态维护FDB表项实现VXLAN通信
    neutron dhcp 高可用
    wpf
    从0到1设计一台8bit计算机
    哇塞的Docker——vscode远程连接Docker容器进行项目开发(三)
    中通消息平台 Kafka 顺序消费线程模型的实践与优化
    飞机大战 python小项目
    看透确定性,抛弃确定性
    如何根据普通ip地址获取当前地理位置
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13474201.html
Copyright © 2011-2022 走看看