美文网首页
[Leetcode212](python):单词搜索II

[Leetcode212](python):单词搜索II

作者: myFamily329 | 来源:发表于2020-01-16 14:57 被阅读0次
1. 题目来源
2. 题目描述

给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:

输入:
words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

输出: ["eat","oath"]

说明:你可以假设所有输入都由小写字母 a-z 组成。

3. 解题思路

根据Trie Tree(字典树/前缀树/单词查找树)对Trie基本结构的描述,编写构建结点,以及构建trie树,以及trie树的基本操作方法。
初始化trie树,并以根结点开始对words数组中的单词进行字典树的创建,完成结果如下:

构建字典树
遍历二维网格boards进行深度搜索,对字典树路径进行匹配。当board[i][j]与node.next[x]不匹配时,node.next[ord(board[i][j]) - ord('a')] == None, 直接返回,若匹配,则把当前board[i][j]标记为已经过,之后进行深度优先遍历,并把board[i][j]加入经过路径path,当node.isEnd == True时,此路径匹配结束,并把此路径加入最后结果集中,并把当前结点node.isEnd置为False。
4. 编程实现
Python
class TrieNode:
    def __init__(self):
        self.isEnd = False
        self.next = [None for i in range(26)]

class Trie:
    def __init__(self):
        self.root = TrieNode()
    
    def insert(self, words):
        node = self.root
        for i in range(len(words)):
            if node.next[ord(words[i]) - ord('a')] == None:
                node.next[ord(words[i]) - ord('a')] = TrieNode()
            node = node.next[ord(words[i]) - ord('a')]
        node.isEnd = True
    
    def search(self, words):
        node = self.root
        for i in range(len(words)):
            if node.next[ord(words[i]) - ord('a')] == None:
                return False
            node = node.next[ord(words[i]) - ord('a')]
        return node.isEnd

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:

        trie = Trie()
        res = []
        node = trie.root
        # 构建字典树
        for word in words:
            trie.insert(word)
        # 深度搜索boards进行路径匹配
        for i in range(len(board)):
            for j in range(len(board[0])):
                self.dfs(board, node, i, j, "", res)
        return res
    

    def dfs(self, board, node, i, j, path, res):
        #结点路径匹配完毕,把存在路径加入结果集中
        if node.isEnd:
            res.append(path)
            #对已经匹配完成的路径,避免二次匹配
            node.isEnd = False

        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] == '#':
            return
        
        temp = board[i][j]
        node = node.next[ord(temp) - ord('a')]
        if not node:
            return
        
        board[i][j] = '#'
        self.dfs(board, node, i + 1, j, path + temp, res)
        self.dfs(board, node, i - 1, j, path + temp, res)
        self.dfs(board, node, i, j + 1, path + temp, res)
        self.dfs(board, node, i, j - 1, path + temp, res)
        # 便于回溯
        board[i][j] = temp

相关文章

  • [Leetcode212](python):单词搜索II

    1. 题目来源 分类:字典树 Leetcode212:单词搜索II 2. 题目描述 给定一个二维网格 board ...

  • leetcode212 单词搜索II

    题目 单词搜索II 暴力解法 暴力解法就是用leetcode79 单词搜索这题的搜索一个单词的dfs方法,挨个搜索...

  • 算法 leetcode212 单词搜索 II

    给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典...

  • leetcode 单词搜索 II python

    第一版先来个爆搜的,对于每一个单词,先找找有没有跟第一个字母相等的,找到后开始向四周找这个单词。后来超时。第二版,...

  • 212. 单词搜索 II

    给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。单词必...

  • LeetCode-140-单词拆分 II

    LeetCode-140-单词拆分 II 140. 单词拆分 II[https://leetcode-cn.com...

  • LeetCode 212.单词搜索 II(212.Word Se

    212. 单词搜索 II 给定一个二维网格 **board **和一个字典中的单词列表 words,找出所有同时在...

  • 力扣 212 单词搜索 II

    题意:给定一个字典和一个字符矩阵,在矩阵找出所有字典中的字符串 思路: 用trie把字典中的单词加入trie中 遍...

  • LintCode 132. 单词搜索 II

    题目描述 给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。一个单词可以从矩阵中的任意...

  • 第五课 ПЯТЫЙ УРОК

    单词 Слова: пятый(数)第五 говорить (动、II)说话、说 стоять (动、II、不及)...

网友评论

      本文标题:[Leetcode212](python):单词搜索II

      本文链接:https://www.haomeiwen.com/subject/sydfzctx.html