37
37
38
38
from typing import List
39
39
40
+
40
41
class Solution :
41
42
def exist (self , board : List [List [str ]], word : str ) -> bool :
42
43
if not board or not word :
43
44
return False
44
45
45
46
m , n = len (board ), len (board [0 ])
46
-
47
+
47
48
# Step 1: Check if all characters in the word exist in the board
48
49
char_count = {}
49
50
for row in board :
@@ -62,18 +63,20 @@ def exist(self, board: List[List[str]], word: str) -> bool:
62
63
def dfs (i , j , word_index ):
63
64
if word_index == len (word ):
64
65
return True
65
-
66
+
66
67
if i < 0 or i >= m or j < 0 or j >= n or board [i ][j ] != word [word_index ]:
67
68
return False
68
69
69
70
temp = board [i ][j ]
70
71
board [i ][j ] = "#" # mark as visited
71
72
72
73
# 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
+ )
77
80
78
81
board [i ][j ] = temp # unmark
79
82
return found
@@ -84,4 +87,4 @@ def dfs(i, j, word_index):
84
87
if board [i ][j ] == word [0 ] and dfs (i , j , 0 ):
85
88
return True
86
89
87
- return False
90
+ return False
0 commit comments