|
| 1 | +```java |
| 2 | +import java.util.ArrayDeque; |
| 3 | +import java.util.Queue; |
| 4 | + |
| 5 | +public class PGM_LV2_게임_맵_최단거리 { |
| 6 | + |
| 7 | + private static final int[] dx = { 0, 1, 0, -1 }; |
| 8 | + private static final int[] dy = { 1, 0, -1, 0 }; |
| 9 | + |
| 10 | + private static int N, M; |
| 11 | + private static int[][] map; |
| 12 | + private static boolean[][] visited; |
| 13 | + private static Queue<Point> q; |
| 14 | + |
| 15 | + private static class Point { |
| 16 | + |
| 17 | + int x; |
| 18 | + int y; |
| 19 | + int cnt; |
| 20 | + |
| 21 | + Point(int x, int y, int cnt) { |
| 22 | + this.x = x; |
| 23 | + this.y = y; |
| 24 | + this.cnt = cnt; |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + |
| 29 | + private static boolean OOB(int x, int y) { |
| 30 | + return x < 0 || N <= x || y < 0 || M <= y; |
| 31 | + } |
| 32 | + |
| 33 | + private static int bfs() { |
| 34 | + q.offer(new Point(0, 0, 1)); |
| 35 | + visited[0][0] = true; |
| 36 | + |
| 37 | + while (!q.isEmpty()) { |
| 38 | + Point cur = q.poll(); |
| 39 | + |
| 40 | + if (cur.x == N - 1 && cur.y == M - 1) return cur.cnt; |
| 41 | + |
| 42 | + for (int d = 0; d < 4; d++) { |
| 43 | + int nx = cur.x + dx[d]; |
| 44 | + int ny = cur.y + dy[d]; |
| 45 | + |
| 46 | + if (OOB(nx, ny) || visited[nx][ny] || map[nx][ny] == 0) continue; |
| 47 | + |
| 48 | + q.offer(new Point(nx, ny, cur.cnt + 1)); |
| 49 | + visited[nx][ny] = true; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return -1; |
| 54 | + } |
| 55 | + |
| 56 | + public int solution(int[][] maps) { |
| 57 | + N = maps.length; |
| 58 | + M = maps[0].length; |
| 59 | + |
| 60 | + map = maps; |
| 61 | + visited = new boolean[N][M]; |
| 62 | + q = new ArrayDeque<>(); |
| 63 | + |
| 64 | + return bfs(); |
| 65 | + } |
| 66 | + |
| 67 | +} |
| 68 | +``` |
0 commit comments