Skip to content

Commit d6b92e3

Browse files
committed
[PGS] 게임 맵 최단거리 / Level 2 / 30분 / 성공
1 parent 85103d7 commit d6b92e3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int solution(int[][] maps) {
5+
int n = maps.length;
6+
int m = maps[0].length;
7+
8+
// 방문여부 리스트
9+
boolean[][] visited = new boolean[n][m];
10+
visited[0][0] = true;
11+
12+
// 방향 벡터 만들기
13+
int[][] dirs ={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
14+
15+
// 큐 선언
16+
Queue<int[]> queue = new LinkedList<>();
17+
queue.offer(new int[]{0, 0});
18+
19+
// BFS 탐색
20+
while (!queue.isEmpty()) {
21+
int[] current = queue.poll();
22+
int x = current[0];
23+
int y = current[1];
24+
25+
for (int[] dir : dirs) {
26+
int nx = x + dir[0];
27+
int ny = y + dir[1];
28+
29+
if ((0 <= nx && nx < n && 0 <= ny && ny < m)
30+
&& !visited[nx][ny]
31+
&& maps[nx][ny] == 1) {
32+
maps[nx][ny] = maps[x][y] + 1;
33+
visited[nx][ny] = true;
34+
queue.add(new int[]{nx, ny});
35+
}
36+
}
37+
}
38+
39+
if (maps[n-1][m-1] != 1) {
40+
return maps[n-1][m-1];
41+
}
42+
return -1;
43+
}
44+
}

0 commit comments

Comments
 (0)