212. Word Search II
Hard
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] words =["oath","pea","eat","rain"]Output:["eat","oath"]
Note:
- All inputs are consist of lowercase letters
a-z. - The values of
wordsare distinct.
笔记:
这个题,题目中的最大的数据,words要大的多,需要将words创建到线段树里面,然后使用dfs去遍历board中的words。
字典树的查找可以省去很多时间,当前缀不一样的时候,会省去查询不必要的word
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for letter in word:
child = node.children.get(letter)
if not child:
child = TrieNode()
node.children[letter] = child
node = child
node.is_word = True
def search(self, word):
node = self.root
for letter in word:
if node.children.get(letter):
node = node.children[letter]
else:
return [False, False]
if node.is_word:
return [True, True]
return [False, True]
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# create trie
trie = Trie()
for word in words:
trie.insert(word)
rlt = []
num_row = len(board)
num_col = len(board[0])
# fina all possible words in board:
def dfs(x, y, node, word):
if not node.children:
return False
if x < 0 or x >= num_row or y < 0 or y >= num_col:
return False
if board[x][y] == -1:
return False
if not node.children.get(board[x][y]):
return
if node.children[board[x][y]].is_word:
rlt.append(word + board[x][y])
temp_word = word + board[x][y]
temp_letter = board[x][y]
board[x][y] = -1
dfs(x, y - 1, node.children[temp_letter], temp_word)
dfs(x - 1, y, node.children[temp_letter], temp_word)
dfs(x, y + 1, node.children[temp_letter], temp_word)
dfs(x + 1, y, node.children[temp_letter], temp_word)
board[x][y] = temp_letter
for i in range(num_row):
for j in range(num_col):
dfs(i, j, trie.root, '')
return list(set(rlt))
本文深入探讨了WordSearch II算法的实现,通过构建字典树优化搜索过程,使用深度优先搜索遍历二维矩阵,寻找所有可能的单词组合,有效地解决了在给定的二维字母板上查找字典中所有单词的问题。

被折叠的 条评论
为什么被折叠?



