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
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)
3713

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



