1
1
// h: height of the board, w: width of the board, n: length of the word
2
2
// Time complexity: O(h * w * 4**n)
3
- // Space complexity: O(h * w + n)
3
+ // Space complexity: O(n)
4
4
5
5
/**
6
6
* @param {character[][] } board
@@ -15,10 +15,6 @@ var exist = function (board, word) {
15
15
const dy = [ 1 , 0 , - 1 , 0 ] ;
16
16
const dx = [ 0 , 1 , 0 , - 1 ] ;
17
17
18
- const checked = Array . from ( { length : h } , ( ) =>
19
- Array . from ( { length : w } , ( ) => 0 )
20
- ) ;
21
-
22
18
let answer = false ;
23
19
24
20
const dfs = ( current , index ) => {
@@ -28,7 +24,8 @@ var exist = function (board, word) {
28
24
}
29
25
30
26
const [ cy , cx ] = current ;
31
- checked [ cy ] [ cx ] = 1 ;
27
+ const value = board [ cy ] [ cx ] ;
28
+ board [ cy ] [ cx ] = "" ;
32
29
33
30
for ( let i = 0 ; i < dy . length ; i ++ ) {
34
31
const ny = cy + dy [ i ] ;
@@ -40,14 +37,14 @@ var exist = function (board, word) {
40
37
ny < h &&
41
38
nx >= 0 &&
42
39
nx < w &&
43
- checked [ ny ] [ nx ] === 0 &&
40
+ board [ ny ] [ nx ] &&
44
41
word [ ni ] === board [ ny ] [ nx ]
45
42
) {
46
43
dfs ( [ ny , nx ] , ni ) ;
47
44
}
48
45
}
49
46
50
- checked [ cy ] [ cx ] = 0 ;
47
+ board [ cy ] [ cx ] = value ;
51
48
} ;
52
49
53
50
for ( let i = 0 ; i < h ; i ++ ) {
0 commit comments