📌 문제 링크
아이템 줍기 - 프로그래머스
Set<String> insidePoint = new HashSet<>();
1 ≤ x, y ≤ 50
이므로 boolean[][]
배열을 선언하고 사각형을 표시함.(3,5)
에서 (4,5)
로 이동해야 하는데, 배열 상에서는 (3,6)
도 이동할 수 있는 곳으로 판단하는 오류 발생.TreeSet
을 사용하여 정답으로 추출되는 모든 값 저장Set<String> answers = new TreeSet<>();
맵의 기본 눈금을 1×1
이 아닌 2×2
로 변경
(1,1)
에 위치한 사각형은 (2,2) ~ (4,4)
로 변환됨.확장된 좌표를 기반으로 boolean[][] map
을 생성
Set<String>
을 활용하여 내부 좌표를 따로 저장.DFS(깊이 우선 탐색)로 최단 경로 탐색
import java.util.*;
class Solution {
Set<String> insidePoint = new HashSet<>();
StringBuilder sb = new StringBuilder();
boolean[][] map = new boolean[111][111];
boolean[][] visited = new boolean[111][111];
int answer = Integer.MAX_VALUE;
// 방향 벡터 (상, 우, 하, 좌)
int[] dix = {-1, 0, 1, 0};
int[] diy = {0, 1, 0, -1};
public int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) {
// 좌표 크기 2배 확장
characterX *= 2;
characterY *= 2;
itemX *= 2;
itemY *= 2;
for (int[] rect : rectangle) {
int x1 = rect[0] * 2, y1 = rect[1] * 2;
int x2 = rect[2] * 2, y2 = rect[3] * 2;
// 사각형 내부 좌표 저장
for (int x = x1 + 1; x <= x2 - 1; x++) {
for (int y = y1 + 1; y <= y2 - 1; y++) {
sb.append(x).append(",").append(y);
insidePoint.add(sb.toString());
sb.setLength(0);
}
}
// 사각형 테두리 좌표를 이동 가능하도록 설정
for (int j = x1; j <= x2; j++) {
map[j][y1] = true;
map[j][y2] = true;
}
for (int j = y1; j <= y2; j++) {
map[x1][j] = true;
map[x2][j] = true;
}
}
// DFS 탐색 시작
visited[characterX][characterY] = true;
dfs(characterX, characterY, 0, itemX, itemY);
return answer / 2; // 최단 거리 반환 (2배 확장한 값이므로 다시 2로 나눔)
}
private void dfs(int cx, int cy, int cnt, int ix, int iy) {
if (cx == ix && cy == iy) {
answer = Math.min(answer, cnt);
}
for (int i = 0; i < 4; i++) {
int dx = cx + dix[i];
int dy = cy + diy[i];
if (dx < 0 || dy < 0 || dx >= 111 || dy >= 111) continue;
if (visited[dx][dy]) continue;
if (!map[dx][dy]) continue;
sb.append(dx).append(",").append(dy);
String tmp = sb.toString();
sb.setLength(0);
if (insidePoint.contains(tmp)) continue;
visited[dx][dy] = true;
dfs(dx, dy, cnt + 1, ix, iy);
visited[dx][dy] = false;
}
}
}
map[][]
및 visited[][]
배열 크기: O(111 × 111) ≈ O(1)
insidePoint
저장 공간: O(N)
, (N: 사각형 내부 좌표 수)O(4^N)
이지만, 백트래킹 및 방문 체크로 O(N^2)
수준으로 최적화됨.O(N)
O(N^2)
(N ≤ 100이므로 충분히 실행 가능)📌 핵심 포인트
answer / 2
처리).Set<String>
을 활용하여 내부 진입 방지.