Skip to content

Commit

Permalink
Time: 4297 ms (44.47%), Space: 16.8 MB (30.15%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
ykdy3951 committed Nov 21, 2024
1 parent 06e88c2 commit 32126b5
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions 0079-word-search/0079-word-search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from collections import deque
class Solution:
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
ans = False

def backtracking(self, x, y, cnt = 0):
if self.ans:
return

if cnt == len(self.word):
self.ans = True
return

for i in range(4):
nx, ny = x + self.dx[i], y + self.dy[i]

if nx < 0 or nx >= self.n or ny < 0 or ny >= self.m or self.vst[nx][ny]:
continue

if self.word[cnt] != self.board[nx][ny]:
continue

self.vst[nx][ny] = True
self.backtracking(nx, ny, cnt + 1)
self.vst[nx][ny] = False


def exist(self, board: List[List[str]], word: str) -> bool:
self.n, self.m = len(board), len(board[0])
self.word = word
self.vst = [[False] * self.m for _ in range(self.n)]
self.board = board

d = deque()
for i in range(self.n):
for j in range(self.m):
if word[0] == board[i][j]:
d.append([i, j, 1])

while d:
x, y, cnt = d.pop()
self.vst[x][y] = True
self.backtracking(x, y, cnt)
self.vst[x][y] = False
if self.ans:
return True

return False

0 comments on commit 32126b5

Please sign in to comment.