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
  • 相关阅读:
    Node.js 调用 restful webservice
    Node.js的集群功能以及在Express的配置
    Node.js 连接mySQL程序
    客户端连接Redis
    缓存的压力测试脚本
    搭建redis集群环境
    编译EXE文件的时候pcap编译不进去。 pyinstaller pcap pypcap 报错
    selenium(五)伪造浏览器
    selenium(四)操作cookie,伪造cookie
    selenium(三)浏览器操作
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13474201.html
Copyright © 2011-2022 走看看