LeetCode 212. Word Search II 5行内Build Trie树

本文介绍了一种在二维字符板上寻找字典中所有单词的算法。通过深度优先搜索(DFS)结合字典树(Trie),实现了高效查找。文章详细展示了如何构建字典树并进行搜索的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

-------------------------------------------------------------------------------------

If defining a Trie class, it needs mutiple lines. But if using a nested dict, the codes look quite clean:

class Solution:
    def dfs(self, board, x, y, rt, rows, cols, res):
        cur_node, cur_ch = rt[board[x][y]], board[x][y]
        if ("$" in cur_node):
            res.append(cur_node["$"])
            cur_node.pop("$")
        board[x][y] = '#'
        for (dx, dy) in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            nx, ny = x + dx, y + dy
            if (nx < rows and nx >= 0 and ny < cols and ny >= 0 and board[nx][ny] != '#' and board[nx][ny] in cur_node):
                self.dfs(board, nx, ny, cur_node, rows, cols, res)
        board[x][y] = cur_ch

    def findWords(self, board, words):
        trie, res = {}, []
        for word in words:
            node = trie
            for ch in word:
                node = node.setdefault(ch, {})
            node["$"] = word
        print(trie)
        rows, cols = len(board), len(board[0]) if len(board) > 0 else 0
        if (cols == 0):
            return []
        for i in range(rows):
            for j in range(cols):
                if (board[i][j] in trie):
                    self.dfs(board, i, j, trie, rows, cols, res)
        return res

s = Solution()
board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
print(s.findWords(board, words))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值