File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(M * N * 4^W)
2+ // SC: O(MIN)
3+ // W: word.length, MIN: min(M * N, W)
4+
5+ /**
6+ * @param {character[][] } board
7+ * @param {string } word
8+ * @return {boolean }
9+ */
10+ var exist = function ( board , word ) {
11+ let result = false ;
12+
13+ for ( let r = 0 ; r < board . length ; r ++ ) {
14+ for ( let c = 0 ; c < board [ 0 ] . length ; c ++ ) {
15+ dfs ( r , c , 0 ) ;
16+ }
17+ }
18+
19+ return result ;
20+
21+ function dfs ( row , column , wordIndex ) {
22+ if ( ! isValid ( row , column ) ) {
23+ return ;
24+ }
25+ if ( board [ row ] [ column ] !== word [ wordIndex ] ) {
26+ return ;
27+ }
28+ if ( wordIndex === word . length - 1 ) {
29+ result = true ;
30+ return ;
31+ }
32+
33+ const temp = board [ row ] [ column ] ;
34+ board [ row ] [ column ] = "#" ;
35+ dfs ( row + 1 , column , wordIndex + 1 ) ;
36+ dfs ( row - 1 , column , wordIndex + 1 ) ;
37+ dfs ( row , column + 1 , wordIndex + 1 ) ;
38+ dfs ( row , column - 1 , wordIndex + 1 ) ;
39+ board [ row ] [ column ] = temp ;
40+ }
41+
42+ function isValid ( row , column ) {
43+ if ( row < 0 || board . length <= row ) {
44+ return false ;
45+ }
46+ if ( column < 0 || board [ 0 ] . length <= column ) {
47+ return false ;
48+ }
49+ return true ;
50+ }
51+ } ;
You can’t perform that action at this time.
0 commit comments