3737
3838from typing import List
3939
40+
4041class Solution :
4142 def exist (self , board : List [List [str ]], word : str ) -> bool :
4243 if not board or not word :
4344 return False
4445
4546 m , n = len (board ), len (board [0 ])
46-
47+
4748 # Step 1: Check if all characters in the word exist in the board
4849 char_count = {}
4950 for row in board :
@@ -62,18 +63,20 @@ def exist(self, board: List[List[str]], word: str) -> bool:
6263 def dfs (i , j , word_index ):
6364 if word_index == len (word ):
6465 return True
65-
66+
6667 if i < 0 or i >= m or j < 0 or j >= n or board [i ][j ] != word [word_index ]:
6768 return False
6869
6970 temp = board [i ][j ]
7071 board [i ][j ] = "#" # mark as visited
7172
7273 # Explore all possible directions
73- found = (dfs (i + 1 , j , word_index + 1 ) or
74- dfs (i - 1 , j , word_index + 1 ) or
75- dfs (i , j + 1 , word_index + 1 ) or
76- dfs (i , j - 1 , word_index + 1 ))
74+ found = (
75+ dfs (i + 1 , j , word_index + 1 )
76+ or dfs (i - 1 , j , word_index + 1 )
77+ or dfs (i , j + 1 , word_index + 1 )
78+ or dfs (i , j - 1 , word_index + 1 )
79+ )
7780
7881 board [i ][j ] = temp # unmark
7982 return found
@@ -84,4 +87,4 @@ def dfs(i, j, word_index):
8487 if board [i ][j ] == word [0 ] and dfs (i , j , 0 ):
8588 return True
8689
87- return False
90+ return False
0 commit comments