1+ import java .util .*;
2+
3+ class Node {
4+
5+ private int index ;
6+ private int distance ;
7+
8+ public Node (int index , int distance ) {
9+ this .index = index ;
10+ this .distance = distance ;
11+ }
12+
13+ public int getIndex () {
14+ return this .index ;
15+ }
16+
17+ public int getDistance () {
18+ return this .distance ;
19+ }
20+ }
21+
22+ public class Main {
23+
24+ public static int n , m ;
25+ public static int [][] graph = new int [201 ][201 ];
26+
27+ // 이동할 네 가지 방향 정의 (상, 하, 좌, 우)
28+ public static int dx [] = {-1 , 1 , 0 , 0 };
29+ public static int dy [] = {0 , 0 , -1 , 1 };
30+
31+ public static int bfs (int x , int y ) {
32+ // 큐(Queue) 구현을 위해 queue 라이브러리 사용
33+ Queue <Node > q = new LinkedList <>();
34+ q .offer (new Node (x , y ));
35+ // 큐가 빌 때까지 반복하기
36+ while (!q .isEmpty ()) {
37+ Node node = q .poll ();
38+ x = node .getIndex ();
39+ y = node .getDistance ();
40+ // 현재 위치에서 4가지 방향으로의 위치 확인
41+ for (int i = 0 ; i < 4 ; i ++) {
42+ int nx = x + dx [i ];
43+ int ny = y + dy [i ];
44+ // 미로 찾기 공간을 벗어난 경우 무시
45+ if (nx < 0 || nx >= n || ny < 0 || ny >= m ) continue ;
46+ // 벽인 경우 무시
47+ if (graph [nx ][ny ] == 0 ) continue ;
48+ // 해당 노드를 처음 방문하는 경우에만 최단 거리 기록
49+ if (graph [nx ][ny ] == 1 ) {
50+ graph [nx ][ny ] = graph [x ][y ] + 1 ;
51+ q .offer (new Node (nx , ny ));
52+ }
53+ }
54+ }
55+ // 가장 오른쪽 아래까지의 최단 거리 반환
56+ return graph [n - 1 ][m - 1 ];
57+ }
58+
59+ public static void main (String [] args ) {
60+ Scanner sc = new Scanner (System .in );
61+
62+ // N, M을 공백을 기준으로 구분하여 입력 받기
63+ n = sc .nextInt ();
64+ m = sc .nextInt ();
65+ sc .nextLine (); // 버퍼 지우기
66+
67+ // 2차원 리스트의 맵 정보 입력 받기
68+ for (int i = 0 ; i < n ; i ++) {
69+ String str = sc .nextLine ();
70+ for (int j = 0 ; j < m ; j ++) {
71+ graph [i ][j ] = str .charAt (j ) - '0' ;
72+ }
73+ }
74+
75+ // BFS를 수행한 결과 출력
76+ System .out .println (bfs (0 , 0 ));
77+ }
78+
79+ }
0 commit comments