Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 23, 2017 13:31
Show Gist options
  • Save cixuuz/5d6d74dfc31f486f2d975bbcf4059f72 to your computer and use it in GitHub Desktop.
Save cixuuz/5d6d74dfc31f486f2d975bbcf4059f72 to your computer and use it in GitHub Desktop.
[79. Word Search] #leetcode
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