Created
October 7, 2024 19:42
-
-
Save hongtaoh/15486725e4277c5f4e2cc7e7fcd55f63 to your computer and use it in GitHub Desktop.
Solution to Leetcode 79 Word Search
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 exist(self, board: List[List[str]], word: str) -> bool: | |
ROWS, COLS = len(board), len(board[0]) | |
path = set() | |
def dfs(r, c, i): | |
if i == len(word): | |
return True | |
if (r<0 or c<0 or r>= ROWS or c>= COLS | |
or board[r][c] != word[i] or | |
(r,c) in path | |
) : return False | |
# if any of the above conditions is met, | |
# it won't execute the following lines | |
path.add((r,c)) | |
res = ( | |
dfs(r-1, c, i+1) or | |
dfs(r+1, c, i+1) or | |
dfs(r, c-1, i+1) or | |
dfs(r, c+1, i+1) | |
) | |
path.remove((r,c)) | |
return res | |
for r in range(ROWS): | |
for c in range(COLS): | |
if dfs(r, c, 0): return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment