Skip to content

Commit 2f799bb

Browse files
committed
Solve: exist
1 parent f25dcc6 commit 2f799bb

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

word-search/daehyun99.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from collections import defaultdict
2+
class Solution:
3+
def exist(self, board: List[List[str]], word: str) -> bool:
4+
pos = defaultdict(list)
5+
for i in range(len(board)):
6+
for j in range(len(board[0])):
7+
if board[i][j] in word:
8+
tmp = pos.get(board[i][j], [])
9+
tmp.append([i, j])
10+
pos[board[i][j]] = tmp
11+
12+
paths = pos.get(word[0], [])
13+
paths = [[path] for path in paths]
14+
15+
for w in word[1:]:
16+
temp = []
17+
18+
while len(paths) > 0:
19+
path = paths.pop()
20+
i , j = path[-1]
21+
if ([i, j+1] in pos[w]) and ([i, j+1] not in path):
22+
temp.append(path[:] + [[i, j+1]])
23+
if ([i, j-1] in pos[w]) and ([i, j-1] not in path):
24+
temp.append(path[:] + [[i, j-1]])
25+
if ([i+1, j] in pos[w]) and ([i+1, j] not in path):
26+
temp.append(path[:] + [[i+1, j]])
27+
if ([i-1, j] in pos[w]) and ([i-1, j] not in path):
28+
temp.append(path[:] + [[i-1, j]])
29+
paths.extend(temp)
30+
for path in paths:
31+
if len(path) == len(word):
32+
return True
33+
return False

0 commit comments

Comments
 (0)