Skip to content

Commit 1465b01

Browse files
committed
word-search
1 parent 967b3c3 commit 1465b01

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

โ€Žword-search/changhyumm.pyโ€Ž

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def exist(self, board: List[List[str]], word: str) -> bool:
3+
rows, cols = len(board), len(board[0])
4+
visited = set()
5+
6+
def dfs(row, col, idx):
7+
# ๋๊นŒ์ง€ ํƒ์ƒ‰์‹œ ๊ธธ์ด์™€ k๊ฐ€ ๊ฐ™์•„์ง€๋ฏ€๋กœ True ๋ฐ˜ํ™˜
8+
if idx == len(word):
9+
return True
10+
# ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚œ ๊ฒฝ์šฐ, ๋ฐฉ๋ฌธํ•œ ๊ฒฝ์šฐ, ๊ฐ™์€ word๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ False ๋ฐ˜ํ™˜
11+
if not (0 <= row < rows) or not (0 <= col < cols) or (row, col) in visited or board[row][col] != word[idx]:
12+
return False
13+
14+
visited.add((row, col))
15+
res = dfs(row + 1, col, idx + 1) or dfs(row - 1, col, idx + 1) or dfs(row, col + 1, idx + 1) or dfs(row, col - 1, idx + 1)
16+
visited.remove((row, col))
17+
return res
18+
# ์‹œ์ž‘์  ํƒ์ƒ‰
19+
for row in range(rows):
20+
for col in range(cols):
21+
if dfs(row, col, 0):
22+
return True
23+
# ์‹œ๊ฐ„๋ณต์žก๋„ O(len(row)*len(col)*4^(word))
24+
return False

0 commit comments

Comments
ย (0)