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)
相关推荐
2301_765703143 分钟前
C++与自动驾驶系统
开发语言·c++·算法
Ll13045252986 分钟前
Leetcode二叉树 part1
b树·算法·leetcode
鹿角片ljp8 分钟前
力扣9.回文数-转字符双指针和反转数字
java·数据结构·算法
热爱编程的小刘16 分钟前
Lesson04---类与对象(下篇)
开发语言·c++·算法
梦梦代码精43 分钟前
开源、免费、可商用:BuildingAI一站式体验报告
开发语言·前端·数据结构·人工智能·后端·开源·知识图谱
有代理ip1 小时前
成功请求的密码:HTTP 2 开头响应码深度解析
java·大数据·python·算法·php
YYuCChi1 小时前
代码随想录算法训练营第三十四天 | 62.不同路径、63.不同路径||
算法
小明同学011 小时前
[C++进阶] 深度解析AVLTree
c++·算法·visualstudio
CoderCodingNo1 小时前
【GESP】C++五级练习题 luogu-P1031 [NOIP 2002 提高组] 均分纸牌
开发语言·c++·算法
梯度下降中2 小时前
求职面试中的线代知识总结
人工智能·线性代数·算法·机器学习