File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {character[][] } board
3
+ * @param {string } word
4
+ * @return {boolean }
5
+ */
6
+ var exist = function ( board , word ) {
7
+ const rows = board . length ;
8
+ const cols = board [ 0 ] . length ;
9
+
10
+ function backtrack ( row , col , index ) {
11
+ // 종료 조건: 모든 글자를 찾았으면 true
12
+ if ( index === word . length ) return true ;
13
+
14
+ // 범위 밖이거나, 현재 칸 글자가 다르면 false
15
+ if (
16
+ row < 0 ||
17
+ row >= rows ||
18
+ col < 0 ||
19
+ col >= cols ||
20
+ board [ row ] [ col ] !== word [ index ]
21
+ ) {
22
+ return false ;
23
+ }
24
+
25
+ // 방문 처리 (임시로 다른 문자로 바꿔줌)
26
+ const temp = board [ row ] [ col ] ;
27
+ board [ row ] [ col ] = "#" ;
28
+
29
+ // 상하좌우로 이동하면서 다음 글자 찾기
30
+ const found =
31
+ backtrack ( row + 1 , col , index + 1 ) || // 아래
32
+ backtrack ( row - 1 , col , index + 1 ) || // 위
33
+ backtrack ( row , col + 1 , index + 1 ) || // 오른쪽
34
+ backtrack ( row , col - 1 , index + 1 ) ; // 왼쪽
35
+
36
+ // 복구 (다시 원래 문자로 되돌리기)
37
+ board [ row ] [ col ] = temp ;
38
+
39
+ return found ;
40
+ }
41
+
42
+ // board 전체 돌면서 시작점 찾기
43
+ for ( let row = 0 ; row < rows ; row ++ ) {
44
+ for ( let col = 0 ; col < cols ; col ++ ) {
45
+ if ( backtrack ( row , col , 0 ) ) {
46
+ return true ;
47
+ }
48
+ }
49
+ }
50
+
51
+ return false ;
52
+ } ;
You can’t perform that action at this time.
0 commit comments