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)
相关推荐
北山小恐龙2 分钟前
针对性模型压缩:YOLOv8n安全帽检测模型剪枝方案
人工智能·深度学习·算法·计算机视觉·剪枝
涛涛北京3 分钟前
【强化学习实验】- PPO
算法
2301_797312263 分钟前
学习Java29天
java·算法
杜子不疼.17 分钟前
【LeetCode 704 & 34_二分查找】二分查找 & 在排序数组中查找元素的第一个和最后一个位置
算法·leetcode·职场和发展
LYFlied20 分钟前
【每日算法】LeetCode 437. 路径总和 III
前端·算法·leetcode·面试·职场和发展
宵时待雨1 小时前
C语言笔记归纳20:文件操作
c语言·开发语言·笔记·算法
alphaTao3 小时前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode
写写闲篇儿6 小时前
下一个更大元素(一)
数据结构·算法
MobotStone7 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
炽烈小老头8 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法