题目:
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = [“oath”,“pea”,“eat”,“rain”] and board =
[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]
输出: [“eat”,“oath”]
代码
class TrieNode:
def __init__(self):
self.next = [None for i in range(26)]
self.word = None
class Solution(object):
def __init__(self):
self.result = None
self.m = None
self.n = None
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if len(board) == 0 or len(board[0])==0:
return []
root = TrieNode()
self.result = []
# build Trie![在这里插入图片描述](https://blog.csdn.net/u013949069/article/details/78056102)
for word in words:
curr = root
for char in word:
idx = ord(char)-97
if curr.next[idx] == None:
curr.next[idx] = TrieNode()
curr = curr.next[idx]
curr.word = word
# search on the board
self.m, self.n = len(board), len(board[0])
for i in range(self.m):
for j in range(self.n):
self.dfs(board, i, j, root)
return self.result
def dfs(self, board, i, j, curr_node):
tmp = board[i][j]
if tmp == '#' or curr_node.next[ord(tmp) - 97] == None:
return
board[i][j] = '#'
curr_node = curr_node.next[ord(tmp) - 97]
if curr_node.word != None:
self.result.append(curr_node.word)
curr_node.word = None # cannot return immedially as there may still exist longer word
moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for move in moves:
if 0 <= i+move[0] < self.m and 0 <= j+move[1] < self.n:
self.dfs(board, i+move[0], j+ move[1], curr_node)
board[i][j] = tmp
#测试
words = [“oath”,“pea”,“eat”,“rain”]
board =[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]
A=Solution()
A.findWords(board=board,words=words)
print(A.result)