MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / Solution

Class Solution

DFS/WordSearch.py:191–289  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

189import pdb
190
191class Solution(object):
192
193 def exist(self, board, word):
194 """
195 :type board: List[List[str]]
196 :type word: str
197 :rtype: bool
198 """
199 for i, d in enumerate(board):
200 for i2, d2 in enumerate(d):
201 if d2 == word[0]:
202 if self.search(board, i2, i, word):
203 return True
204 return False
205
206 def search(self, board, x, y, word):
207 """
208
209 """
210 if not word:
211 return True
212 # if x == len(board[0][0]) and y == len(board):
213 # return False
214 if board[y][x] != word[0]:
215 return False
216
217 if board[y][x] == word[0]:
218 word = word[1:]
219 temp_data = board[y][x]
220 board[y][x] = '#'
221
222
223 # if not word:
224 # return True
225
226 # up
227 if y-1 >= 0:
228 if board[y-1][x] != '#':
229 if self.search(board, x, y-1, word): # u
230 return True
231 # down
232 if y+1 < len(board):
233 if board[y+1][x] != '#':
234 if self.search(board, x, y+1, word): #d
235 return True
236 # left
237 if x-1 >= 0:
238 if board[y][x-1] != '#':
239 if self.search(board, x-1, y, word): #l
240 return True
241
242 # right
243 if x+1 < len(board[0]):
244 if board[y][x+1] != '#':
245 if self.search(board, x+1, y, word): # r
246 return True
247 board[y][x] = temp_data
248 return False

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected