Skip to content

Commit 4f53d3a

Browse files
author
sejineer
committed
word-search solution
1 parent c82f16f commit 4f53d3a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

word-search/sejineer.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
시간 복잡도: O(N * M * 4^(word_len))
3+
공간 복잡도: O(word_len) 재귀 스택 최대 깊이 word_len
4+
"""
5+
from collections import deque
6+
7+
class Solution:
8+
def exist(self, board: List[List[str]], word: str) -> bool:
9+
n, m = len(board), len(board[0])
10+
word_len = len(word)
11+
12+
def dfs(x: int, y: int, idx: int) -> bool:
13+
if idx == word_len:
14+
return True
15+
if x < 0 or y < 0 or x >= m or y >= n:
16+
return False
17+
if board[y][x] != word[idx]:
18+
return False
19+
20+
tmp, board[y][x] = board[y][x], '#'
21+
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
22+
if dfs(x + dx, y + dy, idx + 1):
23+
return True
24+
25+
board[y][x] = tmp
26+
return False
27+
28+
for i in range(n):
29+
for j in range(m):
30+
if board[i][j] == word[0] and dfs(j, i, 0):
31+
return True
32+
33+
return False

0 commit comments

Comments
 (0)