File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * 조건
3+ * 같은 단어 위치는 한번만 쓰인다
4+ * 이웃해서 연속된 단어가 있는지 찾는다
5+
6+ * 백트래킹
7+ * 모든 원소를 완전탐색하기 위한 목적으로 사용.
8+ * 단순히 완전탐색하는 것이 아니라 조건에 따라서 유망한 노드로 이동.
9+ */
10+ function exist ( board : string [ ] [ ] , word : string ) : boolean {
11+ const m = board . length ;
12+ const n = board [ 0 ] . length ;
13+ const l = word . length ;
14+ const directions = [
15+ [ - 1 , 0 ] , // 상
16+ [ 1 , 0 ] , // 하
17+ [ 0 , - 1 ] , // 좌
18+ [ 0 , 1 ] , // 우
19+ ] ;
20+
21+ const backtrack = (
22+ col : number ,
23+ row : number ,
24+ idx : number ,
25+ visited : Set < string >
26+ ) : boolean => {
27+ if ( idx === l ) {
28+ return true ;
29+ }
30+ if (
31+ col < 0 ||
32+ col >= m ||
33+ row < 0 ||
34+ row >= n ||
35+ board [ col ] [ row ] !== word [ idx ] ||
36+ visited . has ( `${ col } ,${ row } ` )
37+ ) {
38+ return false ;
39+ }
40+
41+ visited . add ( `${ col } ,${ row } ` ) ;
42+
43+ for ( const [ dCol , dRow ] of directions ) {
44+ if ( backtrack ( col + dCol , row + dRow , idx + 1 , visited ) ) {
45+ return true ;
46+ }
47+ }
48+
49+ visited . delete ( `${ col } ,${ row } ` ) ;
50+ return false ;
51+ } ;
52+
53+ for ( let col = 0 ; col < m ; col ++ ) {
54+ for ( let row = 0 ; row < n ; row ++ ) {
55+ if ( backtrack ( col , row , 0 , new Set < string > ( ) ) ) {
56+ return true ;
57+ }
58+ }
59+ }
60+ return false ;
61+ }
62+
63+ // TC: O(m*n*4^l) <= m*n: 보드의 크기, l: 단어의 길이. 최대 4개 방향으로 이동 가능
64+ // SC: O(l) <= 단어 길이만큼 방문 가능
You can’t perform that action at this time.
0 commit comments