-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc_0212_word_search_original.py
65 lines (53 loc) · 1.84 KB
/
lc_0212_word_search_original.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
62
63
64
65
from collections import defaultdict, deque
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
n = len(board[0])
B = n + 2
def g_enumerate():
"""Encode board positions into small numbers"""
for y, row in enumerate(board):
for x, v in enumerate(row):
yield B * y + x, v
def neighbors(p):
"""List of neighboring cells"""
return p + 1, p - 1, p + B, p - B
grid = defaultdict(lambda: None) | dict(g_enumerate())
chars = set(grid.values())
begins = defaultdict(set)
for w in words:
# Only keep words that are possible
if not set(w).difference(chars):
begins[w[0]].add(w)
print(begins)
def bfs():
q = deque()
for p, v in grid:
for w in begins[v]:
q.push((p, 0, w))
while q:
p, i, w = q.popleft()
for p1 in neighbors(p):
if w[i] == grid[p1]:
if i == len(w) - 1:
yield p1, w
else:
q.push((p1, i + 1, w))
found = list(bfs())
print(found)
answer = set()
def dfs(p, w, check=-1, seen=set()):
if check == -len(w):
answer.add(w)
if w in answer:
return # Don't repeat ourselves
seen.add(p)
try:
for p1 in neighbors(p):
if p not in seen and grid[p1] == w[check]:
dfs(p1, w, check - 1, seen)
finally:
seen.remove(p)
for f in found:
dfs(*f)
return list(answer)