From f504060d0304c4a6b22baff4bf8b889e5e23f4e0 Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Thu, 2 Oct 2025 12:51:32 -0400 Subject: [PATCH] Time: 5329 ms (20.02%), Space: 18.1 MB (21.99%) - LeetHub --- 0079-word-search/0079-word-search.py | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 0079-word-search/0079-word-search.py diff --git a/0079-word-search/0079-word-search.py b/0079-word-search/0079-word-search.py new file mode 100644 index 0000000..a0448ab --- /dev/null +++ b/0079-word-search/0079-word-search.py @@ -0,0 +1,35 @@ +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + def existFromStart(x: int, y: int, wordLeft: str, used: Set[Tuple[int, int]]): + if len(wordLeft) == 0: + return True + + if board[x][y] != wordLeft[0]: + return False + + if len(wordLeft) == 1: + return True + + newUsed = used.union(set([(x, y)])) + + if x + 1 < len(board) and (x+1,y) not in used and existFromStart(x + 1, y, wordLeft[1:], newUsed): + return True + + if x - 1 >= 0 and (x-1,y) not in used and existFromStart(x - 1, y, wordLeft[1:], newUsed): + return True + + if y + 1 < len(board[x]) and (x,y+1) not in used and existFromStart(x, y + 1, wordLeft[1:], newUsed): + return True + + if y - 1 >= 0 and (x,y-1) not in used and existFromStart(x, y - 1, wordLeft[1:], newUsed): + return True + + return False + + for i in range(len(board)): + for j in range(len(board[i])): + if existFromStart(i, j, word, set({})): + return True + + return False + \ No newline at end of file