File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {character[][] } board
3+ * @param {string } word
4+ * @return {boolean }
5+ */
6+
7+ // board(N * M), where N is the number of row and M is the number of columns
8+ // L, the length of the word
9+ // TC : O(N * M * 4^L)
10+
11+ // recursion depth : the length of the word (L)
12+ // each recursion call requires constant space.
13+ // SC : O(L)
14+
15+ var exist = function ( board , word ) {
16+ let row = board . length ;
17+ let col = board [ 0 ] . length ;
18+
19+ const dfs = ( r , c , idx ) => {
20+ // search done
21+ if ( idx === word . length ) {
22+ return true ;
23+ }
24+
25+ // row and column are out of range
26+ if ( r < 0 || r >= row || c < 0 || c >= col ) {
27+ return false ;
28+ }
29+
30+ if ( board [ r ] [ c ] !== word [ idx ] ) {
31+ return false ;
32+ }
33+
34+ // word[idx] === board[r][c]
35+ // continue searching for word[idx + 1] in adjacent cells on the board
36+ const temp = board [ r ] [ c ] ;
37+ board [ r ] [ c ] = "visited" ;
38+
39+ const arr = [
40+ [ 1 , 0 ] , // Move down
41+ [ - 1 , 0 ] , // Move up
42+ [ 0 , 1 ] , // Move right
43+ [ 0 , - 1 ] , // Move left
44+ ] ;
45+ for ( const [ up , right ] of arr ) {
46+ if ( dfs ( r + up , c + right , idx + 1 ) ) {
47+ return true ;
48+ }
49+ }
50+
51+ board [ r ] [ c ] = temp ;
52+ return false ;
53+ } ;
54+
55+ for ( let i = 0 ; i < row ; i ++ ) {
56+ for ( let j = 0 ; j < col ; j ++ ) {
57+ if ( dfs ( i , j , 0 ) ) {
58+ return true ;
59+ }
60+ }
61+ }
62+
63+ return false ;
64+ } ;
65+
66+
67+
You can’t perform that action at this time.
0 commit comments