Skip to content

Commit 137592b

Browse files
committed
feat: word-search 알고리즘 리팩토링
- 공간복잡도 개선
1 parent 35cfa41 commit 137592b

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

word-search/jinah92.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
# O(M*N*4^W) times, O(M*N+W) spaces
1+
# O(M*N*4^W) times, O(W) spaces
22
class Solution:
33
def exist(self, board: List[List[str]], word: str) -> bool:
44
rows, cols = len(board), len(board[0])
5-
visited = set()
6-
5+
76
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
87

98
def dfs(row, col, idx):
@@ -13,13 +12,13 @@ def dfs(row, col, idx):
1312
return False
1413
if board[row][col] != word[idx]:
1514
return False
16-
if (row, col) in visited:
17-
return False
1815

19-
visited.add((row, col))
16+
temp_val = board[row][col]
17+
board[row][col] = ""
18+
2019
result = any(dfs(row+r, col+c, idx+1) for (r, c) in directions)
21-
visited.remove((row, col))
2220

21+
board[row][col] = temp_val
2322
return result
2423

2524
return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))

0 commit comments

Comments
 (0)