Created
October 8, 2017 12:53
-
-
Save AvocadosConstant/dd8ba5fa5c5f8efdfee15875cdde691d to your computer and use it in GitHub Desktop.
This file contains 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(object): | |
def exist(self, board, word): | |
""" | |
:type board: List[List[str]] | |
:type word: str | |
:rtype: bool | |
""" | |
return any(char == word[0] and self.search(board, word, x, y, set()) | |
for y, row in enumerate(board) for x, char in enumerate(row)) | |
def search(self, board, word, x, y, visited): | |
if not word: | |
return True | |
if (not (0 <= x < len(board[0])) or | |
not (0 <= y < len(board)) or | |
word[0] != board[y][x]): | |
return False | |
if len(word) == 1: | |
return True | |
visited.add((x, y)) | |
for dx, dy in [(0,1), (1,0), (0,-1), (-1,0)]: | |
if ((x + dx, y + dy) not in visited and | |
self.search(board, word[1:], x + dx, y + dy, visited)): | |
return True | |
visited.discard((x, y)) | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment