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)
相关推荐
charlie1145141919 分钟前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎2 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎2 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia2 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸2 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
一叶知秋063 小时前
数据结构-什么是队列?
数据结构·队列
Jasmine_llq4 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计
小棠师姐4 小时前
支持向量机(SVM)入门:超平面与核函数的通俗解释
算法·python机器学习·支持向量机svm·超平面可视化·核函数应用
zhongvv4 小时前
对单片机C语言指针的一些理解
c语言·数据结构·单片机·指针·汇编语言
im_AMBER4 小时前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表