1
+ def boggleBoard (board , words ):
2
+ trie = Trie ()
3
+ for word in words :
4
+ trie .add (word )
5
+ finalWords = {}
6
+ visited = [[False for lettern in row ] for row in board ]
7
+ for i in range (len (board )):
8
+ for j in range (len (board [i ])):
9
+ explore (i , j , board , trie .root , visited , finalWords )
10
+ return list (finalWords .keys ())
11
+
12
+
13
+ def explore (i , j , board , trie , visited , finalWords ):
14
+ if visited [i ][j ] == True :
15
+ return
16
+ letter = board [i ][j ]
17
+ if letter not in trie :
18
+ return
19
+ visited [i ][j ] = True
20
+ trieNode = trie [letter ]
21
+ if "*" in trieNode :
22
+ finalWords [trieNode ["*" ]] = True
23
+ neighbours = getNeighbours (i , j , board )
24
+ for neighbour in neighbours :
25
+ explore (neighbour [0 ], neighbour [1 ], board , trieNode , visited , finalWords )
26
+ visited [i ][j ] = False
27
+
28
+
29
+ def getNeighbours (i , j , board ):
30
+ neighbours = []
31
+ possibleDirections = [(- 1 , 0 ), (- 1 , 1 ), (0 , 1 ), (1 , 1 ), (1 , 0 ), (1 , - 1 ), (0 , - 1 ), (- 1 , - 1 )]
32
+ for direction in possibleDirections :
33
+ di , dj = direction
34
+ newI , newJ = i + di , j + dj
35
+ if 0 <= newI < len (board ) and 0 <= newJ < len (board [0 ]):
36
+ neighbours .append ([newI , newJ ])
37
+ return neighbours
38
+
39
+
40
+ class Trie :
41
+ def __init__ (self ):
42
+ self .root = {}
43
+ self .endSymbol = "*"
44
+
45
+ def add (self , word ):
46
+ current = self .root
47
+ for letter in word :
48
+ if letter not in current :
49
+ current [letter ] = {}
50
+ current = current [letter ]
51
+ current [self .endSymbol ] = word
0 commit comments