-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0079-word-search.py
More file actions
58 lines (47 loc) · 1.4 KB
/
0079-word-search.py
File metadata and controls
58 lines (47 loc) · 1.4 KB
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
"""
79. Word Search
Submitted: March 30, 2026
Runtime: 973 ms (beats 93.20%)
Memory: 19.39 MB (beats 88.13%)
"""
from collections import Counter
from itertools import chain
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.board = board
self.n = len(board)
self.m = len(board[0])
# preprocess
cb = Counter(chain.from_iterable(board))
cw = Counter(word)
for k in cw.keys():
if cw[k] > cb[k]:
return False
del cb
del cw
self.word = word
return any(
self._exist(i, j, 0, set())
for i in range(self.n)
for j in range(self.m)
if board[i][j] == word[0]
)
def _exist(self, i, j, pos, visited):
word = self.word
if pos >= len(word):
return True
if (i, j) in visited:
return False
elif i >= self.n or j >= self.m:
return False
elif i < 0 or j < 0:
return False
visited = visited | {(i, j)}
if self.board[i][j] == word[pos]:
return (
self._exist(i - 1, j, pos + 1, visited) or
self._exist(i, j - 1, pos + 1, visited) or
self._exist(i + 1, j, pos + 1, visited) or
self._exist(i, j + 1, pos + 1, visited)
)
return False