LeetCode 212 Word Search || (python)

LeetCode 212 Word Search II (python)

分析

想必写这题的你已经写过LeetCode 7979的题解,没写过可以先去写79题。这题第一眼看到好像和79题没什么区别,依然是如下结构

for i in range(row):
	for j in range(col):
		dfs(i, j, res)
return res

DFS

但是这里的dfs还包含一个搜索的过程。如果直接暴力的zaiwords里搜索,估计能达到 O ( n 3 ) O(n^3) O(n3)级别,没忍住看了一眼提示,提示里有字典树,现在明白了,我们先用给定的单词列表words构建出一个字典树,然后在字典树里搜索。

字典树

关于字典树,可以去写写leetcode 208 211两题,在我的github,有我写的答案

Code

# trie tree
class Node:
    def __init__(self):
        self.children = collections.defaultdict(Node)
        self.isWord = False
        
class TrieTree:
    def __init__(self):
        self.root = Node()
    def insert(self, word):
        node = self.root
        for c in word:
            node = node.children[c]
        node.isWord = True
            

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        m, n = len(board), len(board[0])
        
        res = []
        trie = TrieTree()
        node = trie.root
        for word in words:
            trie.insert(word)
            
        direcs = [(0,1),(1,0),(0,-1),(-1,0)]
        
        def dfs(node: Node, path, i, j, res):
            if node.isWord:
                res.append(path[:])
                node.isWord = False
            # dfs的一个出口,边界问题
            if i<0 or i>=m or j<0 or j>=n:
                return
            # 另一个出口,当前遍历到的path并不在字典树里
            tmp = board[i][j]
            node = node.children.get(tmp, None)
            if not node:
                return

            board[i][j] = '#'
            for dx, dy in direcs:
                dfs(node, path+tmp, i+dx, j+dy,  res)
            board[i][j] = tmp
        
        for i in range(m):
            for j in range(n):
                dfs(node, '', i, j, res)
        return res

欢迎一起来参与leetcode刷题项目

刷题的GitHub: github链接.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值