Skip to content

Commit 4bbf292

Browse files
committed
[level 2] Title: 게임 맵 최단거리, Time: 8.67 ms, Memory: 55.1 MB -BaekjoonHub
1 parent 4c7c635 commit 4bbf292

File tree

2 files changed

+40
-32
lines changed

2 files changed

+40
-32
lines changed

프로그래머스/2/1844. 게임 맵 최단거리/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
### 성능 요약
66

7-
메모리: 56.1 MB, 시간: 7.44 ms
7+
메모리: 55.1 MB, 시간: 8.67 ms
88

99
### 구분
1010

@@ -16,7 +16,7 @@
1616

1717
### 제출 일자
1818

19-
2025년 07월 15일 12:03:04
19+
2025년 09월 18일 12:52:56
2020

2121
### 문제 설명
2222

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,47 @@
11
import java.util.*;
22
class 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

Comments
 (0)