Skip to content

Commit c159fc1

Browse files
committed
Add solution for Word Search problem using backtracking
1 parent a5875bc commit c159fc1

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

word-search/gcount85.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
# Intuition
3+
백트래킹으로 풀었습니다.
4+
5+
# Complexity
6+
- Time complexity: O(M*N*3^L) => M*N 보드 한 칸을 모두 방문하며,
7+
word 의 길이(L) 횟수 단계 만큼 탐색해야 한다. 매 단계 탐색할 때는 매번 3갈래씩 길을 찾는다.
8+
9+
- Space complexity: 재귀 스택 O(L), visited 크기 O(L)
10+
"""
11+
12+
13+
class Solution:
14+
def exist(self, board: list[list[str]], word: str) -> bool:
15+
m, n = len(board[0]), len(board)
16+
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
17+
18+
def dfs(x, y, cur_step, visited):
19+
if cur_step == len(word) - 1:
20+
return True
21+
22+
for dx, dy in direction:
23+
nx, ny = x + dx, y + dy
24+
if nx < 0 or ny < 0 or nx >= n or ny >= m:
25+
continue
26+
if board[nx][ny] != word[cur_step + 1]:
27+
continue
28+
if (nx, ny) in visited:
29+
continue
30+
visited.add((nx, ny))
31+
if dfs(nx, ny, cur_step + 1, visited):
32+
return True
33+
visited.discard((nx, ny))
34+
return False
35+
36+
for x, row in enumerate(board):
37+
for y, start_word in enumerate(row):
38+
if word[0] != start_word:
39+
continue
40+
if dfs(x, y, 0, {(x, y)}):
41+
return True
42+
return False

0 commit comments

Comments
 (0)