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