|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class Hexeong { |
| 4 | + static int[][] map; |
| 5 | + static int[] dx = {1, -1, 0, 0}; // 오, 왼, 위, 아래 |
| 6 | + static int[] dy = {0, 0, 1, -1}; |
| 7 | + |
| 8 | + public int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) { |
| 9 | + // 1. 2배 확대된 맵 생성 (최대 50*2 = 100) |
| 10 | + map = new int[101][101]; |
| 11 | + |
| 12 | + for (int[] rec : rectangle) { |
| 13 | + int x1 = rec[0] * 2, y1 = rec[1] * 2, x2 = rec[2] * 2, y2 = rec[3] * 2; |
| 14 | + for (int i = x1; i <= x2; i++) { |
| 15 | + for (int j = y1; j <= y2; j++) { |
| 16 | + // 이미 내부(2)로 판정된 곳은 건드리지 않음 |
| 17 | + if (map[i][j] == 2) continue; |
| 18 | + |
| 19 | + // 테두리인 경우 1, 내부인 경우 2 |
| 20 | + if (i == x1 || i == x2 || j == y1 || j == y2) { |
| 21 | + map[i][j] = 1; |
| 22 | + } else { |
| 23 | + map[i][j] = 2; |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // 2. BFS 탐색 |
| 30 | + return bfs(characterX * 2, characterY * 2, itemX * 2, itemY * 2); |
| 31 | + } |
| 32 | + |
| 33 | + public int bfs(int startX, int startY, int targetX, int targetY) { |
| 34 | + Deque<Position> queue = new ArrayDeque<>(); |
| 35 | + queue.add(new Position(startX, startY, 0)); |
| 36 | + |
| 37 | + boolean[][] visited = new boolean[101][101]; |
| 38 | + visited[startX][startY] = true; |
| 39 | + |
| 40 | + while (!queue.isEmpty()) { |
| 41 | + Position cur = queue.poll(); |
| 42 | + |
| 43 | + // 목표 도달 시 (2배 확대 상태이므로 거리를 2로 나눔) |
| 44 | + if (cur.x == targetX && cur.y == targetY) { |
| 45 | + return cur.dist / 2; |
| 46 | + } |
| 47 | + |
| 48 | + for (int i = 0; i < 4; i++) { |
| 49 | + int nx = cur.x + dx[i]; |
| 50 | + int ny = cur.y + dy[i]; |
| 51 | + |
| 52 | + // 맵 범위 안이고, 테두리(1)이며, 방문하지 않은 곳 탐색 |
| 53 | + if (nx >= 0 && nx <= 100 && ny >= 0 && ny <= 100) { |
| 54 | + if (map[nx][ny] == 1 && !visited[nx][ny]) { |
| 55 | + visited[nx][ny] = true; |
| 56 | + queue.add(new Position(nx, ny, cur.dist + 1)); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return 0; |
| 62 | + } |
| 63 | + |
| 64 | + static class Position { |
| 65 | + int x, y, dist; |
| 66 | + Position(int x, int y, int dist) { |
| 67 | + this.x = x; |
| 68 | + this.y = y; |
| 69 | + this.dist = dist; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments