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)
相关推荐
草莓熊Lotso1 小时前
《C++ Stack 与 Queue 完全使用指南:基础操作 + 经典场景 + 实战习题》
开发语言·c++·算法
敲上瘾1 小时前
单序列和双序列问题——动态规划
c++·算法·动态规划
太过平凡的小蚂蚁1 小时前
策略模式:让算法选择像点菜一样简单
算法·策略模式
时间醉酒1 小时前
数据结构基石:单链表的全面实现、操作详解与顺序表对比
数据结构·链表
科研小白_4 小时前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
Terry Cao 漕河泾4 小时前
基于dtw算法的动作、动态识别
算法
Miraitowa_cheems7 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号7 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区8 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9859 小时前
BCH码编译码仿真与误码率性能分析
算法