Skip to content

Commit 19785ec

Browse files
author
jinbeom
committed
Word Search Solution
1 parent 6f3e43e commit 19785ec

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

word-search/kayden.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 시간복잡도: O(N*M*4^limit) limit: word의 길이
2+
# 공간복잡도: O(N)
3+
class Solution:
4+
def exist(self, board: List[List[str]], word: str) -> bool:
5+
m = len(board)
6+
n = len(board[0])
7+
limit = len(word)
8+
visited = [[False for _ in range(n)] for _ in range(m)]
9+
dx = [0, 0, -1, 1]
10+
dy = [-1, 1, 0, 0]
11+
12+
target = 0
13+
14+
def dfs(x, y, idx):
15+
16+
if idx == limit - 1:
17+
return True
18+
19+
for i in range(4):
20+
nx, ny = x + dx[i], y + dy[i]
21+
22+
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and board[nx][ny] == word[idx + 1]:
23+
visited[nx][ny] = True
24+
if dfs(nx, ny, idx + 1):
25+
return True
26+
visited[nx][ny] = False
27+
28+
return False
29+
30+
for i in range(m):
31+
for j in range(n):
32+
if board[i][j] == word[target]:
33+
visited[i][j] = True
34+
if dfs(i, j, 0):
35+
return True
36+
visited[i][j] = False
37+
38+
return False

0 commit comments

Comments
 (0)