@@ -2,64 +2,65 @@ class TrieNode:
2
2
def __init__ (self ):
3
3
self .children = {}
4
4
self .isWord = False
5
- self .refs = 0
5
+
6
+ class Trie :
7
+ def __init__ (self ):
8
+ self .root = TrieNode ()
6
9
7
10
def addWord (self , word ):
8
- cur = self
9
- cur .refs += 1
11
+ current = self .root
10
12
for c in word :
11
- if c not in cur .children :
12
- cur .children [c ] = TrieNode ()
13
- cur = cur .children [c ]
14
- cur .refs += 1
15
- cur .isWord = True
13
+ if c not in current .children :
14
+ current .children [c ] = TrieNode ()
15
+ current = current .children [c ]
16
+ current .isWord = True
16
17
17
18
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
19
+ node = self . root
20
+ path = [( None , node )]
21
+ for char in word :
22
+ node = node .children [ char ]
23
+ path . append (( char , node ))
24
+ node . isWord = False
24
25
26
+ for i in range (len (path ) - 1 , 0 , - 1 ):
27
+ char , currNode = path [i ][0 ], path [i ][1 ]
28
+ parentNode = path [i - 1 ][1 ]
29
+ if currNode .isWord or currNode .children :
30
+ break
31
+ del parentNode .children [char ]
25
32
26
33
class Solution :
27
34
def findWords (self , board : List [List [str ]], words : List [str ]) -> List [str ]:
28
- root = TrieNode ()
29
- for w in words :
30
- root .addWord (w )
35
+ trie = Trie ()
31
36
32
- ROWS , COLS = len (board ), len (board [0 ])
33
- res , visit = set (), set ()
37
+ # Converting words list to a trie
38
+ for word in words :
39
+ trie .addWord (word )
40
+
41
+ rows , columns = len (board ), len (board [0 ])
42
+ result , visit = set (), set ()
34
43
35
44
def dfs (r , c , node , word ):
36
- if (
37
- r < 0
38
- or c < 0
39
- or r == ROWS
40
- or c == COLS
41
- or board [r ][c ] not in node .children
42
- or node .children [board [r ][c ]].refs < 1
43
- or (r , c ) in visit
44
- ):
45
+ if (r < 0 or c < 0 or
46
+ r == rows or c == columns or
47
+ board [r ][c ] not in node .children or (r , c ) in visit ):
45
48
return
46
49
47
50
visit .add ((r , c ))
48
51
node = node .children [board [r ][c ]]
49
52
word += board [r ][c ]
50
53
if node .isWord :
51
- node .isWord = False
52
- res .add (word )
53
- root .removeWord (word )
54
+ result .add (word )
55
+ trie .removeWord (word )
54
56
55
57
dfs (r + 1 , c , node , word )
56
58
dfs (r - 1 , c , node , word )
57
59
dfs (r , c + 1 , node , word )
58
60
dfs (r , c - 1 , node , word )
59
61
visit .remove ((r , c ))
60
62
61
- for r in range (ROWS ):
62
- for c in range (COLS ):
63
- dfs (r , c , root , "" )
64
-
65
- return list (res )
63
+ for r in range (rows ):
64
+ for c in range (columns ):
65
+ dfs (r , c , trie .root , "" )
66
+ return list (result )
0 commit comments