1
+ /**
2
+ * @param {character[][] } board
3
+ * @param {string } word
4
+ * @return {boolean }
5
+ */
6
+ var exist = function ( board , word ) {
7
+ //word๋ฅผ ์ํํด์ board์ x,y๋ฅผ ์กฐ์ ํ์ฌ, ๊ฐ์ด ์์ผ๋ฉด ๊ณ์ true
8
+ const xLength = board [ 0 ] . length ;
9
+ const yLength = board . length
10
+
11
+ // ์ฒดํฌ ๋ฐฐ์ด: ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ ์ฅ. ๊ฐ DFS๋ง๋ค ์๋ก ์ด๊ธฐํ๋ ํ์๋ ์์ (DFS ๋ด์์ ๋ฐฑํธ๋ํน ์ฒ๋ฆฌํ๋ฏ๋ก)
12
+ const check = Array . from ( { length : yLength } , ( ) => Array ( xLength ) . fill ( false ) ) ;
13
+
14
+
15
+ // ๋จ์ด์ ์ฒซ ๊ธ์์ ์ผ์นํ๋ ์์์ ์ ๋ชจ๋ ์์ง
16
+ const startPoints = [ ]
17
+ for ( let i = 0 ; i < xLength ; i ++ ) {
18
+ for ( let j = 0 ; j < yLength ; j ++ ) {
19
+ if ( board [ j ] [ i ] == word [ 0 ] ) {
20
+ startPoints . push ( [ j , i ] )
21
+ }
22
+ }
23
+ }
24
+ // ๊ฐ ์์์ ์์ DFS ์๋
25
+ for ( let startPoint of startPoints ) {
26
+ // ์๋ชป๋ ๊ธธ๋ก ๊ฐ๋ ๊ฒฝ์ฐ๋ ์๊ธฐ ๋๋ฌธ์ ๋ฐฑํธ๋ ํน์ ๋ฌด์กฐ๊ฑด ํ์ํ๋ค.
27
+ if ( backTracking ( startPoint , board , word , check ) ) return true
28
+ }
29
+
30
+ return false
31
+ } ;
32
+
33
+ function backTracking ( startPoint , board , word , check ) {
34
+ const xLength = board [ 0 ] . length ;
35
+ const yLength = board . length
36
+ const upDownLeftRight = [ [ - 1 , 0 ] , [ 1 , 0 ] , [ 0 , - 1 ] , [ 0 , 1 ] ]
37
+ //์คํํธ ํฌ์ธํธ๋ถํฐ ํด์, ์์ฑ์ด ๊ฐ๋ฅํ์ง๋ฅผ dfs๋ฅผ ํตํด์ ์งํํ๋ค.
38
+ //idx๋ ํ์ฌ ํ์ธํด์ผํ word์ idx์ด๋ค.
39
+ function dfs ( y , x , idx ) {
40
+ if ( idx == word . length ) return true
41
+
42
+ if ( y < 0 || y >= yLength ||
43
+ x < 0 || x >= xLength ||
44
+ check [ y ] [ x ] ||
45
+ board [ y ] [ x ] !== word [ idx ]
46
+ ) return false ;
47
+
48
+ check [ y ] [ x ] = true
49
+ // 4๋ฐฉํฅ ํ์
50
+ for ( let [ dy , dx ] of upDownLeftRight ) {
51
+ //๋ง์ฝ ํ๊ฒ์ ํด๋นํ๋์ง๋ฅผ ํ์ธ์ ๋จผ์ ํด์ผํ ๊ฒ๊ฐ์!
52
+ if ( dfs ( y + dy , x + dx , idx + 1 ) ) return true //4๋ฐฉํฅ์ ๋ํด์ ๋ชจ๋ dfs๋ฅผ ์งํํ๋ค.
53
+
54
+ }
55
+
56
+ //๋ฐฑํธ๋ ํน
57
+ check [ y ] [ x ] = false ;
58
+ return false
59
+
60
+ }
61
+ return dfs ( ...startPoint , 0 )
62
+ }
0 commit comments