Skip to content

Commit 1af7efe

Browse files
committed
feat: Word Search
1 parent e9e0f4d commit 1af7efe

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

word-search/HodaeSsi.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def dfs (self, board, word, visited, y, x, word_idx):
3+
if word_idx == len(word):
4+
return True
5+
6+
if y < 0 or y >= len(board) or x < 0 or x >= len(board[0]) or visited[y][x] or board[y][x] != word[word_idx]:
7+
return False
8+
9+
visited[y][x] = True
10+
for dy, dx in [(1, 0), (-1, 0), (0, -1), (0, 1)]:
11+
if self.dfs(board, word, visited, y + dy, x + dx, word_idx + 1):
12+
return True
13+
visited[y][x] = False
14+
return False
15+
16+
def exist(self, board: List[List[str]], word: str) -> bool:
17+
visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
18+
19+
# find fisrt letter in board
20+
for y in range(len(board)):
21+
for x in range(len(board[0])):
22+
if board[y][x] == word[0]:
23+
visited[y][x] = True
24+
for dy, dx in [(1, 0), (-1, 0), (0, -1), (0, 1)]:
25+
if self.dfs(board, word, visited, y + dy, x + dx, 1):
26+
return True
27+
visited[y][x] = False
28+
return False
29+

0 commit comments

Comments
 (0)