File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ var exist = function ( board , word ) {
2
+ const dfs = ( row , col , index ) => {
3
+ if ( word . length === index ) return true ;
4
+ if (
5
+ row < 0 ||
6
+ col < 0 ||
7
+ row >= board . length ||
8
+ col >= board [ 0 ] . length ||
9
+ board [ row ] [ col ] !== word [ index ]
10
+ )
11
+ return false ;
12
+
13
+ board [ row ] [ col ] = "#" ;
14
+ if (
15
+ dfs ( row + 1 , col , index + 1 ) ||
16
+ dfs ( row , col + 1 , index + 1 ) ||
17
+ dfs ( row - 1 , col , index + 1 ) ||
18
+ dfs ( row , col - 1 , index + 1 )
19
+ )
20
+ return true ;
21
+
22
+ board [ row ] [ col ] = word [ index ] ;
23
+ } ;
24
+
25
+ for ( let row = 0 ; row < board . length ; row ++ ) {
26
+ for ( let col = 0 ; col < board [ row ] . length ; col ++ ) {
27
+ if ( board [ row ] [ col ] === word [ 0 ] && dfs ( row , col , 0 ) ) return true ;
28
+ }
29
+ }
30
+
31
+ return false ;
32
+ } ;
33
+
34
+ // N: board column length / M: board row length / L: word length
35
+ // TC: O(N*M*4^L)
36
+ // SC: O(L)
You can’t perform that action at this time.
0 commit comments