File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ // h: height of the board, w: width of the board, n: length of the word
2+ // Time complexity: O(h * w * 4**n)
3+ // Space complexity: O(h * w + n)
4+
5+ /**
6+ * @param {character[][] } board
7+ * @param {string } word
8+ * @return {boolean }
9+ */
10+ var exist = function ( board , word ) {
11+ const n = word . length ;
12+ const h = board . length ;
13+ const w = board [ 0 ] . length ;
14+
15+ const dy = [ 1 , 0 , - 1 , 0 ] ;
16+ const dx = [ 0 , 1 , 0 , - 1 ] ;
17+
18+ const checked = Array . from ( { length : h } , ( ) =>
19+ Array . from ( { length : w } , ( ) => 0 )
20+ ) ;
21+
22+ let answer = false ;
23+
24+ const dfs = ( current , index ) => {
25+ if ( index === n - 1 ) {
26+ answer = true ;
27+ return ;
28+ }
29+
30+ const [ cy , cx ] = current ;
31+ checked [ cy ] [ cx ] = 1 ;
32+
33+ for ( let i = 0 ; i < dy . length ; i ++ ) {
34+ const ny = cy + dy [ i ] ;
35+ const nx = cx + dx [ i ] ;
36+ const ni = index + 1 ;
37+
38+ if (
39+ ny >= 0 &&
40+ ny < h &&
41+ nx >= 0 &&
42+ nx < w &&
43+ checked [ ny ] [ nx ] === 0 &&
44+ word [ ni ] === board [ ny ] [ nx ]
45+ ) {
46+ dfs ( [ ny , nx ] , ni ) ;
47+ }
48+ }
49+
50+ checked [ cy ] [ cx ] = 0 ;
51+ } ;
52+
53+ for ( let i = 0 ; i < h ; i ++ ) {
54+ for ( let j = 0 ; j < w ; j ++ ) {
55+ if ( board [ i ] [ j ] === word [ 0 ] && ! answer ) {
56+ dfs ( [ i , j ] , 0 ) ;
57+ }
58+ }
59+ }
60+
61+ return answer ;
62+ } ;
You can’t perform that action at this time.
0 commit comments