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
words
are distinct.
-------------------------------------------------------------------------------------
If defining a Trie class, it needs mutiple lines. But if using a nested dict, the codes look quite clean:
class Solution:
def dfs(self, board, x, y, rt, rows, cols, res):
cur_node, cur_ch = rt[board[x][y]], board[x][y]
if ("$" in cur_node):
res.append(cur_node["$"])
cur_node.pop("$")
board[x][y] = '#'
for (dx, dy) in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
nx, ny = x + dx, y + dy
if (nx < rows and nx >= 0 and ny < cols and ny >= 0 and board[nx][ny] != '#' and board[nx][ny] in cur_node):
self.dfs(board, nx, ny, cur_node, rows, cols, res)
board[x][y] = cur_ch
def findWords(self, board, words):
trie, res = {}, []
for word in words:
node = trie
for ch in word:
node = node.setdefault(ch, {})
node["$"] = word
print(trie)
rows, cols = len(board), len(board[0]) if len(board) > 0 else 0
if (cols == 0):
return []
for i in range(rows):
for j in range(cols):
if (board[i][j] in trie):
self.dfs(board, i, j, trie, rows, cols, res)
return res
s = Solution()
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
print(s.findWords(board, words))