-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0212-word-search-ii.py
More file actions
131 lines (105 loc) · 3.69 KB
/
0212-word-search-ii.py
File metadata and controls
131 lines (105 loc) · 3.69 KB
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
# 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
ROW = len(board)
COL = len(board[0])
matchedWords = []
def backtracking(currR: int, currC: int, parent: dict):
letter = board[currR][currC]
currNode = parent[letter]
wordMatch = currNode.pop(WORDKEY, False)
if wordMatch:
matchedWords.append(wordMatch)
board[currR][currC] = "#"
for dR, dC in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nextR = currR + dR
nextC = currC + dC
if 0 <= nextR < ROW and 0 <= nextC < COL and board[nextR][nextC] in currNode:
backtracking(nextR, nextC, currNode)
board[currR][currC] = letter
if not currNode:
parent.pop(letter)
for r in range(ROW):
for c in range(COL):
if board[r][c] in trie:
backtracking(r, c, trie)
return matchedWords
# time complexity: O(m*l + n*4^l)
# space complexity: O(m*l + n)
class TrieNode:
def __init__(self, char=""):
self.children = {}
self.char = char
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 startWith(self, prefix):
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True
def removeChar(self, word):
node = self.root
childList = []
for c in word:
childList.append([node, c])
node = node.children[c]
for parent, childChar in childList[::-1]:
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]:
trie = Trie()
ROW = len(board)
COL = len(board[0])
for word in words:
trie.insert(word)
def backtrack(node: TrieNode, r: int, c: int, word=""):
if node.isEnd:
result.append(word)
node.isEnd = False
trie.removeChar(word)
if 0 <= r < ROW and 0 <= c < COL:
currC = board[r][c]
child = node.children.get(currC)
if child is not None:
word += currC
board[r][c] = None
for dR, dC in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
nextR = r + dR
nextC = c + dC
backtrack(child, nextR, nextC, word)
board[r][c] = currC
result = []
for r in range(ROW):
for c in range(COL):
backtrack(trie.root, r, c)
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))
board = [["a", "b"], ["c", "d"]]
words = ["abcb"]
print(Solution().findWords(board, words))