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)
相关推荐
BS_Li8 分钟前
顺序表和链表
数据结构·链表·顺序表
姜行运26 分钟前
数据结构入门【算法复杂度】
android·c语言·数据结构·算法
wen__xvn34 分钟前
每日一题洛谷P8717 [蓝桥杯 2020 省 AB2] 成绩分析c++
c++·算法·蓝桥杯
Y1nhl36 分钟前
搜广推校招面经五十八
人工智能·深度学习·算法·机器学习·求职招聘·推荐算法·搜索算法
f狐0狸x41 分钟前
【蓝桥杯每日一题】3.25
开发语言·数据结构·c++·算法·蓝桥杯
菜鸟记录44 分钟前
一个简单的用C#实现的分布式雪花ID算法
算法·c#·雪花id
lil_侯昊1 小时前
LeetCode热题100_最长连续序列
java·算法·leetcode
不加冰的红茶要热的1 小时前
【机器学习】什么是支持向量机?
算法·机器学习·支持向量机
九亿AI算法优化工作室&3 小时前
SA模拟退火算法优化高斯回归回归预测matlab代码
人工智能·python·算法·随机森林·matlab·数据挖掘·模拟退火算法
么耶咩_5153 小时前
排序复习_代码纯享
数据结构·算法