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)
相关推荐
LXS_3571 分钟前
Day17 C++提高 之 类模板案例
开发语言·c++·笔记·算法·学习方法
小年糕是糕手2 分钟前
【C++】string类(一)
linux·开发语言·数据结构·c++·算法·leetcode·改行学it
初願致夕霞2 分钟前
LeetCode双指针题型总结
算法·leetcode·职场和发展
努力学算法的蒟蒻2 分钟前
day36(12.17)——leetcode面试经典150
算法·leetcode·面试
sali-tec3 分钟前
C# 基于halcon的视觉工作流-章70 深度学习-Deep OCR
开发语言·人工智能·深度学习·算法·计算机视觉·c#·ocr
绿算技术8 分钟前
在稀缺时代,定义“性价比”新标准
大数据·数据结构·科技·算法·硬件架构
zore_c13 分钟前
【C语言】贪吃蛇游戏超详解(包含音效、颜色、封装成应用等)
c语言·数据结构·笔记·stm32·游戏·链表
一起养小猫17 分钟前
《Java数据结构与算法》第四篇(二)二叉树的性质、定义与链式存储实现
java·数据结构·算法
乌萨奇也要立志学C++18 分钟前
【洛谷】贪心专题之哈夫曼编码 从原理到模板题解析
c++·算法
fie88899 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法