-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathboggleBoard.py
61 lines (54 loc) · 1.69 KB
/
boggleBoard.py
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
def boggleBoard(board, words):
trie = Trie()
for word in words:
trie.add(word)
finalWords = {}
visited = [[False for letter in row] for row in board]
for row in range(len(board)):
for col in range(len(board[row])):
explore(row, col, board, visited, trie.root, finalWords)
return list(finalWords.keys())
def explore(i, j, board, visited, trieNode, finalWords):
if visited[i][j]:
return
letter = board[i][j]
if letter not in trieNode:
return
visited[i][j] = True
trieNode = trieNode[letter]
if "*" in trieNode:
finalWords[trieNode["*"]] = True
neighbors = getNeighbors(board, i, j)
for neighbor in neighbors:
explore(neighbor[0], neighbor[1], board, visited, trieNode, finalWords)
visited[i][j] = False
def getNeighbors(board, i, j):
neighbors = []
if i > 0 and j > 0:
neighbors.append([i-1, j-1])
if i > 0 and j < len(board[0])-1:
neighbors.append([i-1, j+1])
if i < len(board)-1 and j < len(board[0])-1:
neighbors.append([i+1, j+1])
if i < len(board)-1 and j > 0:
neighbors.append([i+1, j-1])
if i > 0:
neighbors.append([i-1, j])
if i < len(board)-1:
neighbors.append([i+1, j])
if j > 0:
neighbors.append([i, j-1])
if j < len(board[0])-1:
neighbors.append([i, j+1])
return neighbors
class Trie:
def __init__(self):
self.root = {}
self.endSymbol = "*"
def add(self, word):
current = self.root
for letter in word:
if letter not in current:
current[letter] = {}
current = current[letter]
current[self.endSymbol] = word