Skip to content

Commit 4d24720

Browse files
committed
079 Word Search
1 parent 707e803 commit 4d24720

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

079 Word Search py3.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a 2D board and a word, find if the word exists in the grid.
4+
5+
The word can be constructed from letters of sequentially adjacent cell, where
6+
"adjacent" cells are those horizontally or vertically neighboring. The same
7+
letter cell may not be used more than once.
8+
9+
Example:
10+
11+
board =
12+
[
13+
['A','B','C','E'],
14+
['S','F','C','S'],
15+
['A','D','E','E']
16+
]
17+
18+
Given word = "ABCCED", return true.
19+
Given word = "SEE", return true.
20+
Given word = "ABCB", return false.
21+
"""
22+
from typing import List
23+
from collections import defaultdict
24+
25+
26+
dirs = [(0, -1), (0, 1), (1, 0), (-1, 0)]
27+
28+
29+
class Solution:
30+
def exist(self, board: List[List[str]], word: str) -> bool:
31+
m, n = len(board), len(board[0])
32+
visited = defaultdict(lambda: defaultdict(bool))
33+
for i in range(m):
34+
for j in range(n):
35+
if board[i][j] == word[0]:
36+
if self.dfs(board, visited, i, j, word, 1):
37+
return True
38+
39+
return False
40+
41+
def dfs(self, board, visited, i, j, word, idx):
42+
visited[i][j] = True
43+
if idx >= len(word):
44+
return True
45+
46+
m, n = len(board), len(board[0])
47+
for di, dj in dirs:
48+
I = i + di
49+
J = j + dj
50+
if 0 <= I < m and 0 <= J < n and not visited[I][J] and board[I][J] == word[idx]:
51+
if self.dfs(board, visited, I, J, word, idx + 1):
52+
return True
53+
54+
visited[i][j] = False # restore
55+
return False
56+
57+
58+
if __name__ == "__main__":
59+
assert Solution().exist([
60+
["A","B","C","E"],
61+
["S","F","E","S"],
62+
["A","D","E","E"]
63+
], "ABCESEEEFS") == True

0 commit comments

Comments
 (0)