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

+33
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)