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)
相关推荐
LabVIEW开发22 分钟前
LabVIEW中算法开发的系统化解决方案与优化
算法·labview
Phoebe鑫23 分钟前
数据结构每日一题day17(链表)★★★★★
数据结构·链表
chenyuhao202428 分钟前
链表面试题7之相交链表
数据结构·算法·链表·面试·c#
Pluchon39 分钟前
硅基计划2.0 学习总结 壹 Java初阶
java·开发语言·学习·算法
PassLink_44 分钟前
[计算机科学#14]:数据结构
数据结构·计算机科学·计算机发展史
仙人掌_lz1 小时前
理解多智能体深度确定性策略梯度MADDPG算法:基于python从零实现
python·算法·强化学习·策略梯度·rl
是代码侠呀1 小时前
从前端视角看网络协议的演进
leetcode·开源·github·github star·github 加星
wjm0410061 小时前
B树和B+树
数据结构·b树
PXM的算法星球1 小时前
一文了解B+树的删除原理
数据结构·b树
C_Liu_2 小时前
C语言:深入理解指针(3)
c语言·数据结构·算法