-
Notifications
You must be signed in to change notification settings - Fork 7
/
word_search.py
30 lines (21 loc) · 884 Bytes
/
word_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Word Search
class Solution(object):
def exist(self, board, word):
def dfs(board, i, j, word):
if len(word) == 0:
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]:
return False
temp = board[i][j]
board[i][j] = "#"
found = dfs(board, i+1, j, word[1:]) or dfs(board, i-1, j, word[1:]) \
or dfs(board, i, j+1, word[1:]) or dfs(board, i, j-1, word[1:])
board[i][j] = temp
return found
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(board, i, j, word):
return True
return False
solution = Solution()
print(solution.exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED"))