ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로그래머스 LV2 - 충돌위험 찾기
    STUDY/ALGORITHM 2025. 2. 10. 21:51

    하.. 정말 고전했다.

    문제를 읽음과 동시에 해법이 얼추 그려졌음에도 불구하고,

    IOB가 어디서 발생하는지 찾느라 아주 애먹었다....

    하나하나 차근히 살펴볼 필요가 있겠다..

     

    import java.util.*;
    
    class Solution {
        public int solution(int[][] points, int[][] routes) {
            List<Robot> robots = new ArrayList<>();
            for (int i = 0; i < routes.length; i++) {
                int robotId = i;
                int currentPointIndex = routes[i][0] - 1;
                robots.add(new Robot(robotId, Arrays.copyOf(points[currentPointIndex],2)));
            }
    
            int answer = 0;
    
            while(!robots.stream().allMatch(r -> r.arrived)){
    
                Map<String,Integer> siteMap = new HashMap<>();
                for (Robot robot : robots) {
                    if(!robot.arrived){
                        int robotId = robot.robotId;
                        int stopIndex = robot.stopIndex;
                        int pointIndex = routes[robotId][stopIndex] - 1;
                        int[] goal = points[pointIndex];
                        robot.move(goal);
                        if(robot.current[0] == goal[0] && robot.current[1] == goal[1]){
                            if(stopIndex + 1 < routes[robotId].length) robot.stopIndex += 1;
                            else robot.arrived = true;
                        }
    
                        String currentSiteKey = Arrays.toString(robot.current);
    
                        int currentSiteCount = siteMap.getOrDefault(currentSiteKey, 0);
                        siteMap.put(currentSiteKey, currentSiteCount + 1);
                    }
    
                }
                answer += siteMap.values().stream().filter(v -> v > 1 ).count();
    
            }
    
            return answer;
    
        }
    
        class Robot{
            int robotId;
            int stopIndex = 0;
            int[] current;
            boolean arrived;
    
            public Robot(int robotId, int[] current){
                this.robotId = robotId;
                this.current = current;
            }
    
            public void move(int[] goal) {
                if (current[0] != goal[0]) {
                    if (goal[0] - current[0] > 0) current[0] += 1;
                    else current[0] -= 1;
                } else if (current[1] != goal[1]) {
                    if (goal[1] - current[1] > 0) current[1] += 1;
                    else current[1] -= 1;
                }
            }
        }
    }

     

    while문 조건을 좀더 예쁘게 처리할 수 있을 것 같지만, 

    타임아웃에 문제는 없을 것 같아 그냥 그대로 뒀다.

    계획을 좀더 철저히 세워서 접근하는 습관을 들여야할 듯 싶다.

Designed by Tistory.