Created
October 23, 2017 13:31
-
-
Save cixuuz/5d6d74dfc31f486f2d975bbcf4059f72 to your computer and use it in GitHub Desktop.
[79. Word Search] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def findWords(self, board, words): | |
""" | |
:type board: List[List[str]] | |
:type words: List[str] | |
:rtype: List[str] | |
""" | |
for i in range(len(board)): | |
for j in range(len(board[0])): | |
if self.dfs(board, word, i, j): | |
return True | |
return False | |
def dfs(self, board, word, i, j): | |
# base case: | |
if not word: | |
return True | |
# corner case: out of boundries | |
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]): | |
return False | |
# do search | |
c = board[i][j] | |
board[i][j] = "#" | |
res = c == word[0] and (self.dfs(board, word[1:], i-1, j) or self.dfs(board, word[1:], i+1, j) or self.dfs(board, word[1:], i, j-1) or self.dfs(board, word[1:], i, j+1)) | |
board[i][j] = c | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment