Skip to content

Commit 1459671

Browse files
committed
Sync LeetCode submission Runtime - 3103 ms (87.67%), Memory - 17.8 MB (36.57%)
1 parent eb2bbf4 commit 1459671

File tree

1 file changed

+39
-29
lines changed

1 file changed

+39
-29
lines changed

0079-word-search/solution.py

Lines changed: 39 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,48 @@
11
# Approach: Depth First Search
2-
# https://leetcode.com/problems/word-search/discuss/2843501/PythonC%2B%2B-faster-than-99-DFS-(explained)
32

4-
from collections import Counter
5-
from itertools import chain
3+
# n = no. of rows, m = no. of columns, l = length of word
4+
# Time: O(n * m * 4^l)
5+
# Space: O(l)
66

77
class Solution:
88
def exist(self, board: List[List[str]], word: str) -> bool:
9-
m, n = len(board), len(board[0])
10-
11-
if len(word) > m * n:
12-
return False
13-
14-
# not enough letters on the board
15-
if not (cnt := Counter(word)) <= Counter(chain(*board)):
9+
if not board or not word:
1610
return False
17-
18-
# Inverse word if it is better to start from the end
19-
if cnt[word[0]] > cnt[word[-1]]:
20-
word = word[::-1]
21-
22-
23-
def dfs(i, j, s):
24-
if s == len(word):
11+
12+
rows, cols = len(board), len(board[0])
13+
14+
def dfs(i, j, k):
15+
# Base case: we've matched all characters in word
16+
if k == len(word):
2517
return True
26-
27-
if 0 <= i < m and 0 <= j < n and board[i][j] == word[s]:
28-
board[i][j] = '#'
29-
adj = [(i, j+1), (i, j-1), (i+1, j), (i-1, j)]
30-
dp = any(dfs(ii, jj, s+1) for ii, jj in adj)
31-
board[i][j] = word[s]
32-
return dp
33-
34-
return False
35-
36-
return any(dfs(i, j, 0) for i, j in product(range(m), range(n)))
18+
19+
# Check boundaries and if current cell matches current character
20+
if (i < 0 or i >= rows or
21+
j < 0 or j >= cols or
22+
board[i][j] != word[k]):
23+
return False
24+
25+
# Mark as visited
26+
temp = board[i][j]
27+
board[i][j] = '#'
28+
29+
# Try all four directions
30+
result = (dfs(i + 1, j, k + 1) or # down
31+
dfs(i - 1, j, k + 1) or # up
32+
dfs(i, j + 1, k + 1) or # right
33+
dfs(i, j - 1, k + 1)) # left
34+
35+
# Restore the cell
36+
board[i][j] = temp
37+
38+
return result
39+
40+
for i in range(rows):
41+
for j in range(cols):
42+
if board[i][j] == word[0]:
43+
if dfs(i, j, 0):
44+
return True
45+
46+
return False
3747

3848

0 commit comments

Comments
 (0)