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)
相关推荐
yongui4783437 分钟前
基于深度随机森林(Deep Forest)的分类算法实现
算法·随机森林·分类
是苏浙1 小时前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
迷途之人不知返2 小时前
数据结构之,栈与队列
数据结构
MATLAB代码顾问2 小时前
多种时间序列预测算法的MATLAB实现
开发语言·算法·matlab
高山上有一只小老虎4 小时前
字符串字符匹配
java·算法
愚润求学4 小时前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
MOONICK4 小时前
数据结构——哈希表
数据结构·哈希算法·散列表
林太白4 小时前
跟着TRAE SOLO学习两大搜索
前端·算法
ghie90905 小时前
图像去雾算法详解与MATLAB实现
开发语言·算法·matlab