Skip to content

Commit 412bf7b

Browse files
committed
word-search solution (py)
1 parent 8deee8d commit 412bf7b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

β€Žword-search/hi-rachel.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# DFS 풀이
2+
# board 높이: m, 넓이: n, w: λ‹¨μ–΄μ˜ 길이
3+
# TC: (m * n * 4^w) -> 4^w μƒν•˜μ’Œμš° 탐색 * κΈ€μžνŒ λ‚΄μ˜ λͺ¨λ“  μ’Œν‘œλ₯Ό μƒλŒ€λ‘œ μˆ˜ν–‰ν•¨
4+
# SC: O(m * n + w) -> traversing μ§‘ν•© λ©”λͺ¨λ¦¬λŠ” κΈ€μžνŒμ˜ 크기의 λΉ„λ‘€ + dfs 호좜 μŠ€νƒμ˜ κΉŠμ΄κ°€ λ‹¨μ–΄μ˜ 길이에 λΉ„λ‘€ν•΄ 증가
5+
6+
class Solution:
7+
def exist(self, board: List[List[str]], word: str) -> bool:
8+
n_rows, n_cols = len(board), len(board[0])
9+
traversing = set()
10+
11+
def dfs(row, col, idx):
12+
if idx == len(word):
13+
return True
14+
if not (0 <= row < n_rows and 0 <= col < n_cols):
15+
return False
16+
if (row, col) in traversing:
17+
return False
18+
if board[row][col] != word[idx]:
19+
return False
20+
21+
traversing.add((row, col))
22+
# μƒν•˜μ’Œμš° 탐색
23+
for (r, c) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
24+
if dfs(row + r, col + c, idx + 1):
25+
return True
26+
traversing.remove((row, col))
27+
return False
28+
29+
for i in range(n_rows):
30+
for j in range(n_cols):
31+
if dfs(i, j, 0):
32+
return True
33+
return False

0 commit comments

Comments
Β (0)