-
Notifications
You must be signed in to change notification settings - Fork 0
/
boggle_board.py
61 lines (54 loc) · 1.72 KB
/
boggle_board.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 i in range(len(board)):
for j in range(len(board[i])):
explore(i, j, board, trie.root, visited, finalWords)
return list(finalWords.keys())
def explore(i, j, board, trieNode, visited, 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(i, j, board)
for neighbor in neighbors:
explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords)
visited[i][j] = False
def getNeighbors(i, j, board):
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