File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def exist (self , board , word ):
3+ def backtrack (i , j , k ):
4+ # If we have checked all characters in the word
5+ if k == len (word ):
6+ return True
7+ # If out of bounds or current cell does not match the word character
8+ if (
9+ i < 0
10+ or i >= len (board )
11+ or j < 0
12+ or j >= len (board [0 ])
13+ or board [i ][j ] != word [k ]
14+ ):
15+ return False
16+
17+ # Temporarily mark the cell as visited
18+ temp = board [i ][j ]
19+ board [i ][j ] = ""
20+
21+ # Explore all possible directions: down, up, right, left
22+ found = (
23+ backtrack (i + 1 , j , k + 1 )
24+ or backtrack (i - 1 , j , k + 1 )
25+ or backtrack (i , j + 1 , k + 1 )
26+ or backtrack (i , j - 1 , k + 1 )
27+ )
28+
29+ # Restore the original value of the cell
30+ board [i ][j ] = temp
31+ return found
32+
33+ # Start from each cell in the board
34+ for i in range (len (board )):
35+ for j in range (len (board [0 ])):
36+ if backtrack (i , j , 0 ):
37+ return True
38+ return False
You can’t perform that action at this time.
0 commit comments