문제
https://school.programmers.co.kr/learn/courses/30/lessons/67256
풀이
일단 핸드폰 번호, 최단 거리, 그래프 관련한 문제가 있으면 무조건 생각해야 하는 방법이 있는데, 위치를 좌표값 (x, y)로 설정하고 상황을 구현하는 것이다.
(예를 들어서 숫자 1번의 위치를 (0, 0)으로 잡으면 숫자 7번의 위치는 (2, 0) , 9번의 위치는 (2, 2)가 된다.)
이렇게 구현 한 다음, 왼손 오른손의 좌표를 (x, y)로 둔 다음 가까운 거리에 따라서 2, 5, 8, 0번의 위치로 왼손, 오른손 좌표를 바꿔주면서 계산해 주면 된다.
여기서 제일 중요한 점은 손가락은 무조건 "상하좌우"로 움직인다는 점이다.
1번에서 5번을 누르는 경로와 0번에서 5번으로 가는 경로의 거리를 따지자면 1번에서 5번으로 가는 대각선이 제일 빠르지만, 해당 지문의 조건에 의하면 무조건 상하좌우로 움직여야 하기 때문에, 1번에서 5번으로 가는 거리와, 0번에서 5번으로 가는 거리는 같다.
이를 고려하여 코드를 작성하면 아래와 같다.
def solution(numbers, hand):
# 왼손, 오른손 좌표
left = [3, 0]
right = [3, 2]
# 각각 케이스
left_case = [1, 4, 7]
right_case = [3, 6, 9]
center_case = [2, 5, 8, 0]
answer = []
for phone_numbers in numbers:
if phone_numbers in left_case:
answer.append("L")
left = [left_case.index(phone_numbers), 0]
elif phone_numbers in right_case:
answer.append("R")
right = [right_case.index(phone_numbers), 2]
else:
center = [center_case.index(phone_numbers), 1]
"""
왼손의 현재 좌표와 중앙에 있는 번호 좌표 (x, y)을 서로 빼서 거리 측정
서로 같으면 손잡는 방향에 따라 누르고, 다르면 거리순에 따라 처리
만약에 대각선으로도 측정이 가능하다면, abs(x-y)가 아닌 (x-y)**2 가 되어야
합니다.
"""
if sum([abs(x - y) for x, y in zip(left, center)]) == sum([abs(x - y) for x, y in zip(right, center)]):
if hand == "right":
answer.append("R")
right = [center_case.index(phone_numbers), 1]
else:
answer.append("L")
left = [center_case.index(phone_numbers), 1]
elif sum([abs(x - y) for x, y in zip(left, center)]) > sum([abs(x - y) for x, y in zip(right, center)]):
answer.append("R")
right = [center_case.index(phone_numbers), 1]
else:
answer.append("L")
left = [center_case.index(phone_numbers), 1]
return "".join(answer)
'Algorithm > Programmers' 카테고리의 다른 글
프로그래머스 LV1 과일 장수 (0) | 2023.05.11 |
---|---|
프로그래머스 LV1 옹알이2 (0) | 2023.05.05 |
프로그래머스 LV1 체육복 (0) | 2023.05.05 |
프로그래머스 LV1 두 개 뽑아서 더하기 (0) | 2023.05.04 |
프로그래머스 LV1 덧칠하기 (0) | 2023.04.28 |