MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / exist

Method exist

python/0079-word-search.py:2–36  ·  view source on GitHub ↗
(self, board: List[List[str]], word: str)

Source from the content-addressed store, hash-verified

1class Solution:
2 def exist(self, board: List[List[str]], word: str) -> bool:
3 ROWS, COLS = len(board), len(board[0])
4 path = set()
5
6 def dfs(r, c, i):
7 if i == len(word):
8 return True
9 if (
10 min(r, c) < 0
11 or r >= ROWS
12 or c >= COLS
13 or word[i] != board[r][c]
14 or (r, c) in path
15 ):
16 return False
17 path.add((r, c))
18 res = (
19 dfs(r + 1, c, i + 1)
20 or dfs(r - 1, c, i + 1)
21 or dfs(r, c + 1, i + 1)
22 or dfs(r, c - 1, i + 1)
23 )
24 path.remove((r, c))
25 return res
26
27 # To prevent TLE,reverse the word if frequency of the first letter is more than the last letter's
28 count = sum(map(Counter, board), Counter())
29 if count[word[0]] > count[word[-1]]:
30 word = word[::-1]
31
32 for r in range(ROWS):
33 for c in range(COLS):
34 if dfs(r, c, 0):
35 return True
36 return False
37
38 # O(n * m * 4^n)

Callers

nothing calls this directly

Calls 3

mapFunction · 0.85
sumFunction · 0.50
dfsFunction · 0.50

Tested by

no test coverage detected