Skip to content

Commit c4b824e

Browse files
committed
word search solution
1 parent c3e1000 commit c4b824e

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

word-search/parkhojeong.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def exist(self, board: List[List[str]], word: str) -> bool:
3+
for i in range(len(board)):
4+
for j in range(len(board[0])):
5+
if self.dfs(board, word, i, j):
6+
return True
7+
8+
return False
9+
10+
def dfs(self, board: List[List[str]], word: str, i: int, j: int):
11+
if board[i][j] != word[0] or board[i][j] == "-1":
12+
return False
13+
if len(word) == 1:
14+
return True
15+
16+
temp_cell = board[i][j]
17+
board[i][j] = "-1"
18+
word = word[1:]
19+
if i >= 1 and self.dfs(board, word, i - 1, j):
20+
return True
21+
22+
if j >= 1 and self.dfs(board, word, i, j - 1):
23+
return True
24+
25+
if i < len(board) - 1 and self.dfs(board, word, i + 1, j):
26+
return True
27+
28+
if j < len(board[0]) - 1 and self.dfs(board, word, i, j + 1):
29+
return True
30+
31+
board[i][j] = temp_cell
32+
return False

0 commit comments

Comments
 (0)