1
+ class Solution :
2
+ def findWords (self , board : List [List [str ]], words : List [str ]) -> List [str ]:
3
+ # Recursive propogation to search for words stemming from a specific index
4
+ def propogate (board : List [List [str ]], row : int , col : int , currentTrie ) -> None :
5
+ if not (0 <= row < len (board )) or not (0 <= col < len (board [0 ])) :
6
+ return
7
+ if board [row ][col ] not in currentTrie :
8
+ return
9
+
10
+ currentTrie = currentTrie [board [row ][col ]]
11
+
12
+ if False in currentTrie :
13
+ self .found .add (currentTrie [False ])
14
+
15
+ newIndices = [(row + 1 , col ), (row - 1 , col ), (row , col + 1 ), (row , col - 1 )]
16
+ for r , c in newIndices :
17
+ if (r , c ) not in self .visited and (0 <= r < len (board )) and (0 <= c < len (board [0 ])):
18
+ self .visited .add ((r , c ))
19
+ propogate (board , r , c , currentTrie )
20
+ self .visited .remove ((r , c ))
21
+
22
+
23
+
24
+ # Parsing through each possible origin index
25
+ self .trie = self .constructTrie (words )
26
+ output = set ()
27
+
28
+ for row in range (len (board )) :
29
+ for col in range (len (board [0 ])) :
30
+ self .visited = set ()
31
+ self .found = set ()
32
+ self .visited .add ((row , col ))
33
+ propogate (board , row , col , self .trie )
34
+
35
+ # Compiling the words we found and removing from
36
+ # our search trie
37
+ for fnd in self .found :
38
+ self .trie = self .removeWordFromTrie (fnd , self .trie )
39
+ output |= self .found
40
+
41
+ return list (output )
42
+
43
+ # Helper method to remove a word from our trie
44
+ def removeWordFromTrie (self , word : str , trie : dict ) -> dict :
45
+ curr = trie
46
+ curr ['Counter' ] = curr .get ('Counter' , 0 ) - 1
47
+
48
+ if curr ['Counter' ] <= 0 :
49
+ return {}
50
+
51
+ for c in word :
52
+ if c not in curr :
53
+ break
54
+
55
+ curr [c ]['Counter' ] = curr [c ].get ('Counter' , 0 ) - 1
56
+ if curr [c ]['Counter' ] <= 0 :
57
+ curr .pop (c )
58
+ break
59
+ curr = curr [c ]
60
+
61
+ if False in curr :
62
+ curr .pop (False )
63
+
64
+ return trie
65
+
66
+
67
+ # Helper method to create our initial trie of words that we're searching for
68
+ def constructTrie (self , words : List [str ]) -> dict :
69
+ trie = {}
70
+
71
+ for word in words :
72
+ curr = trie
73
+ trie ['Counter' ] = trie .get ('Counter' , 0 ) + 1
74
+ for c in word :
75
+ if c not in curr :
76
+ curr [c ] = {}
77
+ curr = curr [c ]
78
+ curr ['Counter' ] = curr .get ('Counter' , 0 ) + 1
79
+ curr [False ] = word
80
+
81
+ return trie
0 commit comments