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)
相关推荐
玄妙尽在颠倒间7 分钟前
雪花算法:从 64 位到 128 位 —— 超大规模分布式 ID 生成器的设计与实现
后端·算法
Star在努力34 分钟前
15-C语言:第15~16天笔记
c语言·笔记·算法
CoovallyAIHub39 分钟前
工业质检新突破!YOLO-pdd多尺度PCB缺陷检测算法实现99%高精度
深度学习·算法·计算机视觉
gb421528739 分钟前
负载均衡算法中的加权随机算法
windows·算法·负载均衡
RXXW_Dor1 小时前
数据结构之线性表
数据结构
xdlka1 小时前
C++初学者4——标准数据类型
开发语言·c++·算法
go54631584652 小时前
大规模矩阵构建与高级算法应用
线性代数·算法·矩阵
向左转, 向右走ˉ2 小时前
为什么分类任务偏爱交叉熵?MSE 为何折戟?
人工智能·深度学习·算法·机器学习·分类·数据挖掘
云边有个稻草人3 小时前
【C++】第十九节—一文万字详解 | AVL树实现
数据结构·c++·avl树·avl树的插入·avl树的旋转·avl树实现·avl树的结构
霜绛3 小时前
机器学习笔记(四)——聚类算法KNN、Kmeans、Dbscan
笔记·算法·机器学习·kmeans·聚类