LeetCode 212 Word Search II (python)
分析
想必写这题的你已经写过LeetCode 79了 79的题解,没写过可以先去写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链接.