Skip to content

Commit 9d9a596

Browse files
committed
feat: Solve word-search problem
1 parent b94c8ab commit 9d9a596

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

word-search/hu6r1s.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution:
2+
"""
3+
1. dfs 방식
4+
dx = [1, -1, 0, 0], dy = [0, 0, 1, -1], visited = [[False] * m for _ in range(n)]
5+
4방향으로 가면서 해당 요소에 단어가 없으면 false
6+
방문한 적이 없어야 하고,
7+
8+
시간복잡도: O(N * L * 4^L)
9+
- N: 보드 크기 (n*m)
10+
- L: 단어 길이
11+
- 모든 좌표에서 DFS 시작 (N회) × 4방향 분기 (4^L) × 슬라이싱 비용 (O(L))
12+
공간복잡도: O(N + L^2)
13+
- visited 배열 O(N)
14+
- 재귀 호출 스택 O(L)
15+
- 문자열 슬라이싱으로 인한 추가 메모리 O(L^2)
16+
17+
"""
18+
def exist(self, board: List[List[str]], word: str) -> bool:
19+
n, m = len(board), len(board[0])
20+
visited = [[False] * m for _ in range(n)]
21+
dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
22+
23+
def dfs(x, y, w):
24+
if not w:
25+
return True
26+
if x < 0 or y < 0 or x >= n or y >= m:
27+
return False
28+
if visited[x][y] or board[x][y] != w[0]:
29+
return False
30+
31+
visited[x][y] = True
32+
33+
for i in range(4):
34+
nx = x + dx[i]
35+
ny = y + dy[i]
36+
if dfs(nx, ny, w[1:]):
37+
return True
38+
39+
visited[x][y] = False
40+
return False
41+
42+
for i in range(n):
43+
for j in range(m):
44+
if dfs(i, j, word):
45+
return True
46+
return False

0 commit comments

Comments
 (0)