Skip to content

Commit 9bdac9e

Browse files
committed
word-search
1 parent 61ec21a commit 9bdac9e

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

word-search/freemjstudio.py

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

0 commit comments

Comments
 (0)