-
Notifications
You must be signed in to change notification settings - Fork 0
/
212 Word Search II.py
45 lines (43 loc) · 1.42 KB
/
212 Word Search II.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
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
# make trie
trie = {}
for w in words:
t = trie
for c in w:
if c not in t:
t[c] = {}
t = t[c]
t['#'] = '#'
self.res = set()
self.used = [[False] * len(board[0]) for _ in xrange(len(board))]
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.find(board, i, j, trie, '')
return list(self.res)
def find(self, board, i, j, trie, pre):
if '#' in trie:
self.res.add(pre)
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return
if not self.used[i][j] and board[i][j] in trie:
self.used[i][j] = True
self.find(board, i + 1, j, trie[board[i][j]], pre + board[i][j])
self.find(board, i, j + 1, trie[board[i][j]], pre + board[i][j])
self.find(board, i - 1, j, trie[board[i][j]], pre + board[i][j])
self.find(board, i, j - 1, trie[board[i][j]], pre + board[i][j])
self.used[i][j] = False
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
S = Solution()
S.findWords(board, words)