Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

79. Word Search #144

Open
jrmullen opened this issue Jul 1, 2024 · 0 comments
Open

79. Word Search #144

jrmullen opened this issue Jul 1, 2024 · 0 comments

Comments

@jrmullen
Copy link
Owner

jrmullen commented Jul 1, 2024

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        height = len(board)
        width = len(board[0])
        used = set()

        def backtrack(h, w, c):
            # Base case
            if c == len(word):
                return True
            
            if (h >= height or h < 0 or w >= width or w < 0 # Tile is out of bounds
                or board[h][w] != word[c] # Tile does not contain the target letter
                or (h, w) in used): # Character has already been used
                return False
            
            # Actions - check all adjacent tiles
            used.add((h, w))
            answer = (backtrack(h, w - 1, c + 1) or backtrack(h, w + 1, c + 1) 
                    or backtrack(h - 1, w, c + 1) or backtrack(h + 1, w, c + 1))
            # Undo the above action
            used.remove((h, w))
            return answer
            
        # Iterate over each tile on the board
        for h in range(height):
            for w in range(width):
                if backtrack(h, w, 0):
                    return True
        
        return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant