프로그래머스 - PCCP 기출문제 3번, 충돌위험 찾기
입력
출력
Map<Integer, int[]> pointMap = new HashMap<>();
for (int i = 0; i < points.length; i++) {
pointMap.put(i + 1, points[i];
}
// 시간별 위치 개수를 저장할 수 있는 Map 선언
// Map<String, Integer> 중 String 대신 다른 자료형을 사용해도 동일하다.
Map<Intger, Map<String, Integer>> timePoisitoinMap = new HashMap<>();
// routes에 경로를 가져와 현재 위치와 다음 목적지를 int[] 배열에 저장
for (int[] route : routes) {
int time = 0;
int[] currentPosition = pointMap.get(route[0]);
// 시작은 0부터하지만, 목적지는 1 ~ N - 1 까지만 체크하면 되기 때문에 시작값 1, 조건 < route.length로 지정
for (int j = 1; j < route.length; j++) {
int[] nextPosition = pointMap.get(route[j]);
// time을 받아야 현재 위치 & 목적지가 변경되었을 때 이어서 기록할 수 있다.
time = moveRobot(currentPosition, nextPosition, time, timePositionMap);
currentPosition = nextPosition;
}
}
// 로봇 위치를 이동 시키고 시간별로 기록
private int moveRobot(int[] currentPosition, int[] nextPositoin, int startTime, Map<Integer, Map<String, Integer>> timePositionMap) {
int r1 = currentPosition[0], c1 = currentPosition[1], r2 = nextPosition[0], c2 = nextPosition[1];
int time = startTime;
// 제일 처음으로 시작할 때의 시간과 위치 저장 ex) {0: {"3,2": 1}}
if (time == 0) {
String positionKey = r1 + "," + c1;
timePositionMap.putIfAbsent(time, new HashMap<>());
Map<String, Integer> positionMap = timePositionMap.get(time);
positionMap.put(positionKey, positionMap.getOrDefault(positionKey, 0) + 1);
}
while (r1 != r2 || c1 != c2) {
if (r1 < r2) r1++;
else if (r1 > r2) r1--;
else if (c1 < c2) c1++;
else c1--;
time++;
String positionKey = r1 + "," + c1;
timePositionMap.putIfAbsent(time, new HashMap<>());
Map<String, Integer> positionMap = timePositionMap.get(time);
positionMap.put(positionKey, positionMap.getOrDefault(positionKey, 0) + 1);
}
return time;
}
for (Map<String, Integer> poisitions : timePositionMap.values()) {
for (int count : positions.values()) {
riskCount++;
}
}