File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(m * n * 4^L), where L is the length of the word
2
+ // Space Complexity: O(L) due to he recursive call stack
3
+
4
+ function exist ( board : string [ ] [ ] , word : string ) : boolean {
5
+ // input: m * n grid of characters board, a string word
6
+ // output: true if word exists in the grid
7
+
8
+ const dfs = ( index : number , row : number , col : number ) => {
9
+ if (
10
+ row < 0 ||
11
+ row >= board . length ||
12
+ col < 0 ||
13
+ col >= board [ 0 ] . length ||
14
+ board [ row ] [ col ] !== word [ index ]
15
+ ) {
16
+ return false ;
17
+ }
18
+
19
+ if ( index === word . length - 1 ) {
20
+ return true ;
21
+ }
22
+
23
+ const visited = board [ row ] [ col ] ;
24
+ board [ row ] [ col ] = "#" ;
25
+
26
+ const result =
27
+ dfs ( index + 1 , row + 1 , col ) ||
28
+ dfs ( index + 1 , row - 1 , col ) ||
29
+ dfs ( index + 1 , row , col + 1 ) ||
30
+ dfs ( index + 1 , row , col - 1 ) ;
31
+
32
+ board [ row ] [ col ] = visited ;
33
+
34
+ return result ;
35
+ } ;
36
+
37
+ for ( let i = 0 ; i < board . length ; i ++ ) {
38
+ for ( let j = 0 ; j < board [ 0 ] . length ; j ++ ) {
39
+ if ( dfs ( 0 , i , j ) ) {
40
+ return true ;
41
+ }
42
+ }
43
+ }
44
+
45
+ return false ;
46
+ }
You can’t perform that action at this time.
0 commit comments