11import java .util .*;
22class Solution {
3+ boolean [][] visited ;
4+ int [] dx = {-1 ,1 ,0 ,0 };
5+ int [] dy = {0 ,0 ,-1 ,1 };
6+ int row ;
7+ int col ;
8+
39 public int solution (int [][] maps ) {
4- int xLength = maps .length ; // x축 길이
5- int yLength = maps [0 ].length ; // y축 길이
6-
7- int [][] move = {{-1 ,0 },{1 ,0 },{0 ,-1 },{0 ,1 }}; // 이동(상하좌우)
8- int [][] distance = new int [xLength ][yLength ]; // 거리 좌표
9-
10- // 좌표 큐
10+ row = maps .length ;
11+ col = maps [0 ].length ;
12+ visited = new boolean [row ][col ];
13+
14+ int answer = bfs (0 ,0 ,1 ,maps );
15+ return answer ;
16+ }
17+
18+ int bfs (int x ,int y , int distance ,int [][] maps ) {
1119 Queue <int []> queue = new LinkedList <>();
12- queue .offer (new int []{0 ,0 });
13- distance [0 ][0 ] = 1 ;
14-
15- while (!queue .isEmpty ()){
16- int [] cur = queue .poll (); // 현재 좌표
17- int x = cur [0 ];
18- int y = cur [1 ];
19-
20- if (x == xLength -1 && y == yLength -1 ) return distance [x ][y ];
21-
22- for (int i = 0 ; i < 4 ; i ++){
23- int dx = x + move [i ][0 ]; // 이동 후 x좌표
24- int dy = y + move [i ][1 ]; // 이동 후 y좌표
25-
26-
27- // 범위 체크
28- if (dx >= 0 && dy >= 0 && dx < xLength && dy < yLength ){
29- // 방문 체크 + 길인지 체크
30- if (maps [dx ][dy ] == 1 && distance [dx ][dy ] == 0 ){
31- queue .add (new int []{dx ,dy }); // 큐 등록
32- distance [dx ][dy ] = distance [x ][y ] + 1 ; // 이전 좌표 +1
33- }
20+ queue .offer (new int []{x ,y ,distance });
21+
22+ while (!queue .isEmpty ()) {
23+ int [] current = queue .poll ();
24+ int currentX = current [0 ];
25+ int currentY = current [1 ];
26+ int currentDistance = current [2 ];
27+ visited [currentX ][currentY ] = true ;
28+
29+ if (currentX == row -1 && currentY == col -1 ) return currentDistance ;
30+
31+ int nextX ;
32+ int nextY ;
33+ for (int i =0 ; i < 4 ; i ++){
34+ nextX = currentX + dx [i ];
35+ nextY = currentY + dy [i ];
36+
37+ // 범위 내에서, 방문한적 없고, 벽이 아님
38+ if (nextX >= 0 && nextX < row && nextY >= 0 && nextY < col && !visited [nextX ][nextY ] && maps [nextX ][nextY ] == 1 ){
39+ visited [nextX ][nextY ] = true ;
40+ queue .offer (new int []{nextX ,nextY ,currentDistance +1 });
3441 }
3542 }
3643 }
37- return -1 ; // 도달 못하는 경우
44+
45+ return -1 ;
3846 }
3947}
0 commit comments