Skip to content

Commit d361988

Browse files
authored
Merge pull request neetcode-gh#328 from AgranatMarkit/main
Update 212-Word-Search-II.py
2 parents d5a38e7 + 543fe85 commit d361988

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

212-Word-Search-II.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,25 @@ class TrieNode:
22
def __init__(self):
33
self.children = {}
44
self.isWord = False
5+
self.refs = 0
56

67
def addWord(self, word):
78
cur = self
9+
cur.refs += 1
810
for c in word:
911
if c not in cur.children:
1012
cur.children[c] = TrieNode()
1113
cur = cur.children[c]
14+
cur.refs += 1
1215
cur.isWord = True
16+
17+
def removeWord(self, word):
18+
cur = self
19+
cur.refs -= 1
20+
for c in word:
21+
if c in cur.children:
22+
cur = cur.children[c]
23+
cur.refs -= 1
1324

1425

1526
class Solution:
@@ -24,14 +35,18 @@ def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
2435
def dfs(r, c, node, word):
2536
if (r < 0 or c < 0 or
2637
r == ROWS or c == COLS or
27-
board[r][c] not in node.children or (r, c) in visit):
38+
board[r][c] not in node.children or
39+
node.children[board[r][c]].refs < 1 or
40+
(r, c) in visit):
2841
return
2942

3043
visit.add((r, c))
3144
node = node.children[board[r][c]]
3245
word += board[r][c]
3346
if node.isWord:
47+
node.isWord = False
3448
res.add(word)
49+
root.removeWord(word)
3550

3651
dfs(r + 1, c, node, word)
3752
dfs(r - 1, c, node, word)

0 commit comments

Comments
 (0)