1
+ const local_input = `
2
+ 4 6
3
+ 101111
4
+ 101010
5
+ 101011
6
+ 111011
7
+ ` ;
8
+
9
+ const input = process . execArgv . includes ( "--stack-size=65536" )
10
+ ? require ( "fs" ) . readFileSync ( "dev/stdin" ) . toString ( )
11
+ : local_input ;
12
+
13
+ const lines = input . trim ( ) . split ( '\n' ) ;
14
+
15
+ const [ N , M ] = lines [ 0 ] . split ( ' ' ) . map ( Number ) ;
16
+ const map = lines . slice ( 1 ) . map ( el => el . split ( '' ) ) ;
17
+ const history = new Set ( [ '0,0' ] ) ;
18
+ const tree = [
19
+ new Set ( [ '0,0' ] ) ,
20
+ ]
21
+
22
+ for ( let i = 1 ; i <= N * M ; i ++ ) {
23
+ const lastSet = tree [ tree . length - 1 ] ;
24
+ const newSet = new Set ( ) ;
25
+ lastSet . forEach ( str => {
26
+ const [ y , x ] = str . split ( ',' ) . map ( Number ) ;
27
+
28
+ if ( y - 1 >= 0 && y - 1 < N && map [ y - 1 ] [ x ] === '1' ) { // 위
29
+ const str = `${ y - 1 } ,${ x } ` ;
30
+
31
+ if ( ! history . has ( str ) ) {
32
+ newSet . add ( str )
33
+ history . add ( str )
34
+ }
35
+ }
36
+ if ( y + 1 >= 0 && y + 1 < N && map [ y + 1 ] [ x ] === '1' ) { // 아래
37
+ const str = `${ y + 1 } ,${ x } ` ;
38
+
39
+ if ( ! history . has ( str ) ) {
40
+ newSet . add ( str )
41
+ history . add ( str )
42
+ }
43
+ }
44
+ if ( x - 1 >= 0 && x - 1 < M && map [ y ] [ x - 1 ] === '1' ) { // 왼쪽
45
+ const str = `${ y } ,${ x - 1 } ` ;
46
+
47
+ if ( ! history . has ( str ) ) {
48
+ newSet . add ( str )
49
+ history . add ( str )
50
+ }
51
+ }
52
+ if ( x + 1 >= 0 && x + 1 < M && map [ y ] [ x + 1 ] === '1' ) { // 오른쪽
53
+ const str = `${ y } ,${ x + 1 } ` ;
54
+
55
+ if ( ! history . has ( str ) ) {
56
+ newSet . add ( str )
57
+ history . add ( str )
58
+ }
59
+ }
60
+
61
+ } )
62
+
63
+ if ( newSet . has ( `${ N - 1 } ,${ M - 1 } ` ) ) {
64
+ console . log ( tree . length + 1 )
65
+ return null
66
+ }
67
+
68
+ tree . push ( newSet ) ;
69
+ }
0 commit comments