-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0212-word-search-ii.py
134 lines (110 loc) · 3.91 KB
/
0212-word-search-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# time complexity: O(M(4*3^(L-1)))
# space complexity: O(n)
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
WORDKEY = "$"
trie = {}
for word in words:
node = trie
for letter in word:
node = node.setdefault(letter, {})
node[WORDKEY] = word
rowNum = len(board)
colNum = len(board[0])
matchedWords = []
def backtracking(row, col, parent):
letter = board[row][col]
currNode = parent[letter]
wordMatch = currNode.pop(WORDKEY, False)
if wordMatch:
matchedWords.append(wordMatch)
board[row][col] = "#"
for rowOffset, colOffset in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
newRow, newCol = row + rowOffset, col + colOffset
if (
newRow < 0
or newRow >= rowNum
or newCol < 0
or newCol >= colNum
):
continue
if not board[newRow][newCol] in currNode:
continue
backtracking(newRow, newCol, currNode)
board[row][col] = letter
if not currNode:
parent.pop(letter)
for row in range(rowNum):
for col in range(colNum):
if board[row][col] in trie:
backtracking(row, col, trie)
return matchedWords
# time complexity: O(n*3^l)
# space complexity: O(m)
class TrieNode:
def __init__(self, char=""):
self.char = char
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children.get(c)
node.isEnd = True
def startsWith(self, prefix):
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True
def removeChars(self, word):
node = self.root
childList = []
for c in word:
childList.append([node, c])
node = node.children[c]
for parent, childChar in reversed(childList):
target = parent.children[childChar]
if target.children:
return
del parent.children[childChar]
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
def dfs(trieForWords: Trie, node: TrieNode, grid: List[List[str]], row: int, col: int, result: List[str], word=""):
if node.isEnd:
result.append(word)
node.isEnd = False
trieForWords.removeChars(word)
if 0 <= row < ROW and 0 <= col < COL:
char = grid[row][col]
child = node.children.get(char)
if child is not None:
word += char
grid[row][col] = None
for dR, dC in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
dfs(trieForWords, child, grid,
row + dR, col + dC, result, word)
grid[row][col] = char
ROW = len(board)
COL = len(board[0])
trieForWords = Trie()
result = []
for word in words:
trieForWords.insert(word)
for r in range(ROW):
for c in range(COL):
dfs(trieForWords, trieForWords.root, board, r, c, result)
return result
board = [["o", "a", "a", "n"],
["e", "t", "a", "e"],
["i", "h", "k", "r"],
["i", "f", "l", "v"]]
words = ["oath", "pea", "eat", "rain"]
print(Solution().findWords(board, words))