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+ //! dfs 구현 중에 막혀서 ai의 도움을 받아 풀이를 완성했습니다..
2+ var exist = function ( board , word ) {
3+ const dx = [ 0 , 0 , - 1 , 1 ] ;
4+ const dy = [ - 1 , 1 , 0 , 0 ] ;
5+
6+ for ( let i = 0 ; i < board . length ; i ++ ) {
7+ for ( let j = 0 ; j < board [ i ] . length ; j ++ ) {
8+ if ( board [ i ] [ j ] === word [ 0 ] ) {
9+ if ( dfs ( j , i , 0 ) ) return true ;
10+ }
11+ }
12+ }
13+
14+ function dfs ( x , y , index ) {
15+ // 성공
16+ if ( index === word . length ) return true ;
17+
18+ // 실패
19+ if ( x < 0 || y < 0 || y >= board . length || x >= board [ y ] . length ) return false ;
20+ if ( board [ y ] [ x ] === '#' ) return false ;
21+ if ( board [ y ] [ x ] !== word [ index ] ) return false ;
22+
23+ // 방문 표시
24+ const origin = board [ y ] [ x ] ;
25+ board [ y ] [ x ] = '#' ;
26+
27+ // 탐색
28+ for ( let i = 0 ; i < 4 ; i ++ ) {
29+ const newDy = y + dy [ i ] ;
30+ const newDx = x + dx [ i ] ;
31+
32+ if ( dfs ( newDx , newDy , index + 1 ) ) return true ;
33+ }
34+ // 복원
35+ board [ y ] [ x ] = origin ;
36+
37+ return false ;
38+ }
39+
40+ return false ;
41+ } ;
You can’t perform that action at this time.
0 commit comments