1
+
2
+ /**
3
+ * Time Complexity: O(m * n * 4^k)
4
+ * Space Complexity: O(m * n)
5
+ */
6
+ function exist ( board : string [ ] [ ] , word : string ) : boolean {
7
+ // Initialize the board dimensions
8
+ const m = board . length ;
9
+ const n = board [ 0 ] . length ;
10
+
11
+ const dfs = ( i : number , j : number , index : number ) : boolean => {
12
+ // If we've matched all characters, return true
13
+ if ( index === word . length ) return true ;
14
+ // If out of bounds or current character doesn't match, return false
15
+ if ( i < 0 || i >= m || j < 0 || j >= n || board [ i ] [ j ] !== word [ index ] ) return false ;
16
+
17
+ // Temporarily mark the current cell as visited
18
+ const temp = board [ i ] [ j ] ;
19
+ board [ i ] [ j ] = '#' ;
20
+
21
+ // Explore all four possible directions
22
+ const found =
23
+ dfs ( i + 1 , j , index + 1 ) ||
24
+ dfs ( i - 1 , j , index + 1 ) ||
25
+ dfs ( i , j + 1 , index + 1 ) ||
26
+ dfs ( i , j - 1 , index + 1 ) ;
27
+
28
+ // Unmark the current cell (backtracking)
29
+ board [ i ] [ j ] = temp ;
30
+
31
+ // Return true if we found the word
32
+ return found ;
33
+ } ;
34
+
35
+ // Iterate through each cell in the board
36
+ for ( let i = 0 ; i < m ; i ++ ) {
37
+ for ( let j = 0 ; j < n ; j ++ ) {
38
+ // Start DFS from each cell
39
+ if ( dfs ( i , j , 0 ) ) return true ;
40
+ }
41
+ }
42
+
43
+ // If we didn't find the word, return false
44
+ return false ;
45
+ }
0 commit comments