Skip to content

Commit 88f6f34

Browse files
committed
solve : work-search
1 parent 9eb0fb8 commit 88f6f34

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

word-search/samthekorean.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution:
2+
def exist(self, board, word):
3+
def backtrack(i, j, k):
4+
# If we have checked all characters in the word
5+
if k == len(word):
6+
return True
7+
# If out of bounds or current cell does not match the word character
8+
if (
9+
i < 0
10+
or i >= len(board)
11+
or j < 0
12+
or j >= len(board[0])
13+
or board[i][j] != word[k]
14+
):
15+
return False
16+
17+
# Temporarily mark the cell as visited
18+
temp = board[i][j]
19+
board[i][j] = ""
20+
21+
# Explore all possible directions: down, up, right, left
22+
found = (
23+
backtrack(i + 1, j, k + 1)
24+
or backtrack(i - 1, j, k + 1)
25+
or backtrack(i, j + 1, k + 1)
26+
or backtrack(i, j - 1, k + 1)
27+
)
28+
29+
# Restore the original value of the cell
30+
board[i][j] = temp
31+
return found
32+
33+
# Start from each cell in the board
34+
for i in range(len(board)):
35+
for j in range(len(board[0])):
36+
if backtrack(i, j, 0):
37+
return True
38+
return False

0 commit comments

Comments
 (0)