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+ /**
2+ * @param {character[][] } board
3+ * @param {string } word
4+ * @return {boolean }
5+ */
6+ var exist = function ( board , word ) {
7+
8+ let tempResult = false ;
9+
10+ for ( let i = 0 ; i < board . length ; i ++ ) {
11+ for ( let j = 0 ; j < board [ 0 ] . length ; j ++ ) {
12+ if ( board [ i ] [ j ] === word [ 0 ] ) {
13+ tempResult = dfs ( i , j , 0 ) ;
14+ if ( tempResult ) {
15+ return true ;
16+ }
17+ } else {
18+ continue ;
19+ }
20+ }
21+ }
22+
23+
24+ return tempResult ;
25+
26+
27+
28+ function dfs ( x , y , currentIndex ) {
29+
30+ if ( x < 0 || y < 0 || x >= board . length || y >= board [ 0 ] . length ) {
31+ return false ;
32+ }
33+
34+ if ( board [ x ] [ y ] !== word [ currentIndex ] ) {
35+ return false ;
36+ }
37+
38+ let nextIndex = currentIndex + 1 ;
39+
40+ if ( nextIndex === word . length ) {
41+ return true ;
42+ }
43+
44+ let tempChar = board [ x ] [ y ] ;
45+ board [ x ] [ y ] = '*' ;
46+
47+
48+ let hasCharOnTheLeft = dfs ( x - 1 , y , nextIndex ) ;
49+ let hasCharOnTheRight = dfs ( x + 1 , y , nextIndex ) ;
50+ let hasCharAtTheTop = dfs ( x , y + 1 , nextIndex ) ;
51+ let hasCharAtTheBottom = dfs ( x , y - 1 , nextIndex ) ;
52+
53+ board [ x ] [ y ] = tempChar ;
54+
55+ return hasCharOnTheLeft || hasCharOnTheRight || hasCharAtTheTop || hasCharAtTheBottom ;
56+ }
57+ } ;
You can’t perform that action at this time.
0 commit comments