Skip to content

Commit 00bdcdb

Browse files
author
sangbeenmoon
committed
solved word-search.
1 parent 518ed71 commit 00bdcdb

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

word-search/sangbeenmoon.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# TC : O(m * n * 4^L)
2+
# SC : O(m * n + L)
3+
4+
class Solution:
5+
answer = False
6+
dx = [0,0,-1,1]
7+
dy = [-1,1,0,0]
8+
9+
def exist(self, board: List[List[str]], word: str) -> bool:
10+
11+
for yy in range(len(board)):
12+
for xx in range(len(board[0])):
13+
if board[yy][xx] == word[0]:
14+
self.visited = [ [False] * len(board[0]) for _ in range(len(board))]
15+
self.visited[yy][xx] = True
16+
self.dfs(board, word, xx, yy, 0)
17+
18+
19+
return self.answer
20+
21+
def dfs(self, board, word, cx, cy, idx):
22+
print(cx, cy, idx)
23+
if idx == len(word) - 1:
24+
self.answer = True
25+
26+
for i in range(4):
27+
nx = cx + self.dx[i]
28+
ny = cy + self.dy[i]
29+
30+
if 0 <= nx and nx < len(board[0]):
31+
if 0 <= ny and ny < len(board):
32+
if self.visited[ny][nx] == False:
33+
if idx + 1 <= len(word) - 1 and word[idx+1] == board[ny][nx]:
34+
self.visited[ny][nx] = True
35+
self.dfs(board, word, nx, ny, idx + 1)
36+
self.visited[ny][nx] = False

0 commit comments

Comments
 (0)