212. Word Search II 字典树(Trie)

本文深入探讨了WordSearch II算法的实现,通过构建字典树优化搜索过程,使用深度优先搜索遍历二维矩阵,寻找所有可能的单词组合,有效地解决了在给定的二维字母板上查找字典中所有单词的问题。

212. Word Search II

Hard

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

 

Example:

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

Output: ["eat","oath"]

 

Note:

  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

 

笔记:

这个题,题目中的最大的数据,words要大的多,需要将words创建到线段树里面,然后使用dfs去遍历board中的words。

字典树的查找可以省去很多时间,当前缀不一样的时候,会省去查询不必要的word

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for letter in word:
            child = node.children.get(letter)
            if not child:
                child = TrieNode()
                node.children[letter] = child
            node = child
        node.is_word = True

    def search(self, word):
        node = self.root
        for letter in word:
            if node.children.get(letter):
                node = node.children[letter]
            else:
                return [False, False]
        if node.is_word:
            return [True, True]
        return [False, True]

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        # create trie
        trie = Trie()
        for word in words:
            trie.insert(word)
        rlt = []
        num_row = len(board)
        num_col = len(board[0])
        # fina all possible words in board:
        def dfs(x, y, node, word):
            if not node.children:
                return False
            if x < 0 or x >= num_row or y < 0 or y >= num_col:
                return False
            if board[x][y] == -1:
                return False
            if not node.children.get(board[x][y]):
                return
            if node.children[board[x][y]].is_word:
                rlt.append(word + board[x][y])
            temp_word = word + board[x][y]
            temp_letter = board[x][y]
            board[x][y] = -1
            dfs(x, y - 1, node.children[temp_letter], temp_word)
            dfs(x - 1, y, node.children[temp_letter], temp_word)
            dfs(x, y + 1, node.children[temp_letter], temp_word)
            dfs(x + 1, y, node.children[temp_letter], temp_word)
            board[x][y] = temp_letter

        for i in range(num_row):
            for j in range(num_col):
                dfs(i, j, trie.root, '')
        return list(set(rlt))

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值