Skip to content

Commit

Permalink
word-search solution
Browse files Browse the repository at this point in the history
  • Loading branch information
sungjinwi committed Jan 3, 2025
1 parent 32e1e4c commit 7f4e8ad
Showing 1 changed file with 40 additions and 27 deletions.
67 changes: 40 additions & 27 deletions word-search/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,47 @@
"""
ํ’€์ด :
์ƒํ•˜์ขŒ์šฐ ์ด๋™ํ•œ ์ขŒํ‘œ๊ฐ€ board๋ฒ”์œ„ ๋ฒ—์–ด๋‚˜๋ฉด False
board[m][n]์ด word[idx]์™€ ๋ถˆ์ผ์น˜ํ•˜๋ฉด False
์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ์„๊ฒฝ์šฐ False
๋‹จ์–ด๊ฐ€ ์™„์„ฑ๋˜๋ฉด True
์ƒํ•˜์ขŒ์šฐ ํ•œ์นธ ์ด๋™ํ•œ์นธ์— ๋Œ€ํ•ด ์žฌ๊ท€์  ํ˜ธ์ถœ
์ƒํ•˜์ขŒ์šฐ ์ค‘ True ์žˆ์œผ๋ฉด True ์—†์œผ๋ฉด False
TC : O(M * N * 4 ^ W)
board์˜ ํฌ๊ธฐ์— ๋น„๋ก€ -> M * N
๋‹จ์–ด์˜ ๊ธธ์ด ๋งŒํผ ์ƒํ•˜์ขŒ์šฐ ์žฌ๊ท€ ํ˜ธ์ถœ -> 4 ^ W
SC : O(M * N + W)
set์˜ ๋ฉ”๋ชจ๋ฆฌ๋Š” board ํฌ๊ธฐ์— ๋น„๋ก€ -> M * N
ํ•จ์ˆ˜ ํ˜ธ์ถœ ์Šคํƒ์€ ๋‹จ์–ด ๊ธธ์ด์— ๋น„๋ก€ -> W
"""

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
visit = {}
visit = set()

def dfs(m: int, n: int, idx: int) -> bool:
if not (0 <= m < row and 0 <= n < col):
return False
if not board[m][n] == word[idx]:
return False
if (m, n) in visit:
return False
if idx == len(word) - 1:
return True

visit.add((m, n))
if any (dfs(m + r, n + c, idx + 1) \
for (r, c) in [(1, 0), (-1, 0), (0, 1), (0, -1)]):
return True
visit.remove((m, n))
return False

row = len(board)
col = len(board[0])

def dfs(m : int, n : int, seq : str) :
if visit[m, n] :
return
if not word.startswith(seq + board[m][n]) :
return
visit[(m, n)] = 1
seq += board[m][n]
if seq == word :
return
if m > 0 :
if (dfs()) :
return True
if down :
dfs()
if left :
dfs()
if right :
dfs()
visit(m, n) = 0
seq = seq[:len(seq)-1]


while m in range(row) :
while n in range(col) :
if dfs(m, n, "") :
for m in range(row):
for n in range(col):
if dfs(m, n, 0):
return True
visit.clear()
return False

0 comments on commit 7f4e8ad

Please sign in to comment.