본문 바로가기
프로그래머스/Lv.2

[PCCP 기출문제] 3번 > 충돌위험 찾기 - Python, Counter

by 아찌방 2025. 2. 27.

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/340211

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

코드 & 풀이

 

from collections import Counter

def solution(points, routes):
    # 출발지부터 도착지까지 검사해야 됨
    # 출발지에서 검사 한 번 하고 시작 or 공회전 한 번 돌리고 시작
    new_routes = []
    for route in routes:
        step = 0
        x, y = points[route[0] - 1]
        tmp_route = [(x, y, step)] # 출발지 기록
        
        for i in range(len(route) - 1):
            start_x, start_y = points[route[i] - 1]
            end_x, end_y = points[route[i + 1] - 1]
                        
            while start_x != end_x or start_y != end_y: # 다음 point까지 이동하기
                if start_x != end_x: # x 좌표 이동
                    start_x += 1 if start_x < end_x else -1
                elif start_y != end_y: # y 좌표 이동
                    start_y += 1 if start_y < end_y else -1
                step += 1
                tmp_route.append((start_x, start_y, step))
                
        new_routes += tmp_route
    
    counter = Counter(new_routes)
    return sum(1 for i in counter.values() if i > 1)

 

다음 포인터로 가는 길을

 

걸음 수와 함께 모두 체크한다.

 

그리고 이를 Counter를 통해 확인한다.

 

주의점

 

맨 처음 출발 위치에서 겹치는 것도 체크해야하기에

 

시작하기 전에 먼저 삽입해둔다.

 

그리고 나는 x좌표 먼저 움직이고 싶어서

 

조건문에 x 좌표 비교를 넣어줬지만

 

y좌표부터 움직이고 싶다면

 

y좌표를 먼저 넣어줘도 된다.

 

 

 

 

 

다음에 또 봐요

 

728x90