Skip to content

Commit 5e4ec0b

Browse files
committed
add solution: word-search
1 parent cd49973 commit 5e4ec0b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

β€Žword-search/ZetBe.pyβ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
Docstring for word-search.ZetBe
3+
문제: 2D λ³΄λ“œμ—μ„œ 단어λ₯Ό μ°ΎμœΌμ‹œμ˜€.
4+
풀이: 깊이 μš°μ„  탐색(DFS)을 μ‚¬μš©ν•˜μ—¬ λ³΄λ“œμ˜ 각 μ…€μ—μ„œ μ‹œμž‘ν•˜μ—¬ 단어λ₯Ό μ°ΎμŠ΅λ‹ˆλ‹€. λ°©λ¬Έν•œ 셀은 λ‹€μ‹œ λ°©λ¬Έν•˜μ§€ μ•Šλ„λ‘ ν‘œμ‹œν•©λ‹ˆλ‹€.
5+
μ‹œκ°„ λ³΅μž‘λ„: O(m * n * 3^k), mκ³Ό n은 λ³΄λ“œμ˜ ν–‰κ³Ό μ—΄μ˜ 수, kλŠ” λ‹¨μ–΄μ˜ κΈΈμ΄μž…λ‹ˆλ‹€. 각 μ…€μ—μ„œ μ‹œμž‘ν•˜μ—¬ μ΅œλŒ€ 3κ°€μ§€ λ°©ν–₯으둜 탐색할 수 μžˆμœΌλ―€λ‘œ 전체 μ‹œκ°„ λ³΅μž‘λ„λŠ” O(m * n * 3^k)μž…λ‹ˆλ‹€.
6+
곡간 λ³΅μž‘λ„: O(k), kλŠ” λ‹¨μ–΄μ˜ κΈΈμ΄μž…λ‹ˆλ‹€. μž¬κ·€ 호좜 μŠ€νƒμ΄ μ΅œλŒ€ k κΉŠμ΄κΉŒμ§€ μŒ“μΌ 수 μžˆμœΌλ―€λ‘œ 곡간 λ³΅μž‘λ„λŠ” O(k)μž…λ‹ˆλ‹€.
7+
μ‚¬μš©ν•œ 자료ꡬ쑰: ν•¨μˆ˜(μž¬κ·€ 호좜 μŠ€νƒ), 2D 리슀트(λ°©λ¬Έ ν‘œμ‹œ)
8+
'''
9+
10+
class Solution:
11+
def exist(self, board: List[List[str]], word: str) -> bool:
12+
answ = False
13+
dx, dy = [0, 1, -1, 0], [1, 0, 0, -1]
14+
def dfs(x, y, i, v):
15+
nonlocal answ
16+
if i == len(word):
17+
answ = True
18+
return True
19+
if board[y][x] != word[i-1]:
20+
return False
21+
for j in range(4):
22+
ny, nx = y+dy[j], x+dx[j]
23+
if 0 <= ny < len(board) and 0 <= nx < len(board[0]) and v[ny][nx] == 0 and board[ny][nx] == word[i]:
24+
v[ny][nx] = 1
25+
dfs(nx, ny, i+1, v)
26+
v[ny][nx] = 0
27+
28+
for i in range(len(board)):
29+
for j in range(len(board[0])):
30+
v = [[0 for i in range(len(board[0]))] for j in range(len(board))]
31+
if board[i][j] == word[0]:
32+
v[i][j] = 1
33+
dfs(j, i, 1, v)
34+
35+
return answ
36+
37+

0 commit comments

Comments
Β (0)