Leetcode 212. Word Search II

Problem

Given an m x n board of characters and a list of strings words, return all words on the board.

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

Algorithm

Use Trie for save and search word, run dfs find the word in the board.

Code

python3 复制代码
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        
        class Trie:
            def __init__(self):
                self.root = {}

            def insert(self, word):
                node = self.root
                for c in word:
                    if c not in node:
                        node[c] = {}
                    node = node[c]
                node['leaf'] = word  

        trie = Trie()
        for word in words:
            trie.insert(word)

        m, n = len(board), len(board[0])
        result = []

        def dfs(x, y, node):
            c = board[x][y]
            if c not in node:
                return
            next_node = node[c]
            word = next_node.get('leaf')
            if word:
                result.append(word)
                next_node['leaf'] = None # need remove

            board[x][y] = '#'
            for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
                nx, ny = x + dx, y + dy
                if 0 <= nx < m and 0 <= ny < n and board[nx][ny] != '#':
                    dfs(nx, ny, next_node)
            board[x][y] = c

        for i in range(m):
            for j in range(n):
                dfs(i, j, trie.root)

        return list(result)
相关推荐
我是咸鱼不闲呀4 分钟前
力扣Hot100系列21(Java)——[多维动态规划]总结(不同路径,最小路径和,最长回文子串,最长公共子序列, 编辑距离)
java·leetcode·动态规划
lihao lihao7 分钟前
二分查找
java·数据结构·算法
WolfGang00732110 分钟前
代码随想录算法训练营 Day15 | 二叉树 part05
数据结构·算法
sheeta199810 分钟前
LeetCode 每日一题笔记 2025.03.20 3567.子矩阵的最小绝对差
笔记·leetcode·矩阵
代码栈上的思考10 分钟前
消息队列持久化:文件存储设计与实现全解析
java·前端·算法
qq_4176950520 分钟前
内存对齐与缓存友好设计
开发语言·c++·算法
2301_8166512221 分钟前
实时系统下的C++编程
开发语言·c++·算法
2401_8318249622 分钟前
C++与Python混合编程实战
开发语言·c++·算法
2301_8166512229 分钟前
C++中的策略模式高级应用
开发语言·c++·算法