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
  • 相关阅读:
    jquery 添加关键字小插件
    打印出所有每一位都与其他位不重复的自然数
    尾递归版,斐波那契数列
    如何在移动端宽度自适应实现正方型?
    css隐藏元素的六类13种方法
    如何给行内元素设置宽高?
    css实现垂直水平居中的方法
    pwa
    目录树生成工具treer
    服务端返回的json数据,导致前端报错的原因及解决方法
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13474201.html
Copyright © 2011-2022 走看看