212-word-search-ii¶
Try it on leetcode
Description¶
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.
Example 1:

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"]
Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
is a lowercase English letter.1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.- All the strings of
words
are unique.
Solution(Python)¶
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for w in word:
if w not in node:
node[w] = {}
node = node[w]
node['#'] = word
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = Trie()
for word in words:
trie.insert(word)
m, n = len(board), len(board[0])
dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
res = []
def dfs(root, i, j):
c = board[i][j]
if c not in root:
return
child = root[c]
word = child.pop('#', None)
if word:
res.append(word)
if not child:
root.pop(c)
board[i][j] = '#'
for dx, dy in dirs:
x = i + dx
y = j + dy
if 0 <= x < m and 0 <= y < n:
dfs(child, x, y)
board[i][j] = c
for i in range(m):
for j in range(n):
dfs(trie.root, i, j)
return res