- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path79.py
48 lines (39 loc) · 1.37 KB
/
79.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
'''
classSolution(object):
defexist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
result=False
forrowinrange(len(board)):
forcolinrange(len(board[0])):
ifself.dfs(board, word, row, col, 0):
returnTrue
returnFalse
defdfs(self, board, word, row, col, curr_len):
ifrow<0orcol<0orrow>=len(board) orcol>=len(board[0]):
returnFalse
ifboard[row][col] ==word[curr_len]:
c=board[row][col]
board[row][col] ='#'
ifcurr_len==len(word) -1:
returnTrue
elif (self.dfs(board, word, row-1, col, curr_len+1) orself.dfs(board, word, row+1, col, curr_len+1) orself.dfs(board, word, row, col-1, curr_len+1) orself.dfs(board, word, row, col+1, curr_len+1)):
returnTrue
board[row][col] =c
returnFalse