(코딩테스트) 프로그래머스 - PCCP 3번, 충돌위험 찾기 (JAVA)

Kwon Donghyun·2024년 10월 31일
0

코딩테스트

목록 보기
1/2

프로그래머스 - PCCP 기출문제 3번, 충돌위험 찾기

입력

  • points : n개의 좌표(r, c)를 담은 2차원 정수 배열
  • routes : x대의 운송 경로를 담은 2차원 정수 배열

출력

  • 위험 상황 횟수(이동 중 같은 좌표에 2대 이상의 로봇이 모인 경우)

  1. 포인트별 위치
    points에 순서대로 있는 point들을 Map으로 저장
Map<Integer, int[]> pointMap = new HashMap<>();

for (int i = 0; i < points.length; i++) {
	pointMap.put(i + 1, points[i];
}
  1. 경로 추적 후 시간별 위치 저장
    시간별 위치 개수를 저장할 수 있는 Map 선언
    routes에 경로를 가져와 현재 위치와 다음 목적지를 int[] 배열에 저장
    로봇 위치를 이동 시키고 시간별로 기록
// 시간별 위치 개수를 저장할 수 있는 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;
}
  1. 시간별 위치의 값에서 횟수가 2 이상인 값들 체크 후 카운트
for (Map<String, Integer> poisitions : timePositionMap.values()) {
	for (int count : positions.values()) {
    	riskCount++;
    }
}

회고

  • 이 문제를 처음 봤을 때 시간별 위치 기록을 생각하지 못해서 배열로 선언 후 계산만 하려했다.
  • 로직은 완성했으나 시작할 때 시간 & 위치 기록 부분과 시작 위치 & 목적지 변경될 때 이전 목적지 기록과 변경된 시작 위치 기록의 중복을 해결하기 위한 방법을 생각했어야 했다.
  • Map을 사용할 때 Map<Integer, int[]> 나 Map<Integer, Map<String, Intger>>를 생각하지 못하거나 제대로 구현하지 못 했던 경우가 있었는데 이번 기회에 제대로 공부해서 잘 사용하도록 몸에 익혀야겠다.

0개의 댓글