알고리즘, 자료구조/프로그래머스

[Python] 방문 길이

jaee 2026. 1. 2. 14:15

문제

링크: https://school.programmers.co.kr/learn/courses/30/lessons/49994

 

프로그래머스

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

programmers.co.kr

 

게임 캐릭터를 4가지 명령어를 통해 움직일 때, 게임 캐릭터가 지나간 길 중 캐릭터가 처음 걸어본 길의 길이를 구하는 함수 작성.

  • U: 위쪽으로 한칸 이동
  • D: 아래쪽으로 한칸 이동
  • R: 오른쪽으로 한칸 이동
  • L: 왼쪽으로 한칸 이동

캐릭터는 좌표평면의 (0,0) 위치에서 시작하며, 좌표평면의 경계는 (-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있다. 좌표 평면의 경계를 넘어가는 명령어는 무시한다

# 제한 사항
dirs는 string형으로 주어지며, 'U', 'D', 'R', 'L' 이외에 문자는 주어지지 않음
dirs의 길이는 500 이하의 자연수

 

풀이

처음에 작성한 코드

def solution(dirs):
    curr_point = (0,0)
    routes = set()
    
    for d in dirs:
    	# 현재 좌표를 시작점으로 두고
        start_point = curr_point
        
        # 조건에 해당하면 x, y 좌표 이동
        if d == 'U' and curr_point[1] < 5:
            curr_point = (curr_point[0], curr_point[1] + 1)
        elif d == 'D' and curr_point[1] > -5:
            curr_point = (curr_point[0], curr_point[1] - 1)
        elif d == 'R' and curr_point[0] < 5:
            curr_point = (curr_point[0] + 1, curr_point[1])
        elif d == 'L' and curr_point[0] > -5:
            curr_point = (curr_point[0] - 1, curr_point[1])
        else:
            continue
            
        routes.add(tuple(sorted((start_point, curr_point))))
        
    return len(routes)

 

가독성 개선한 코드

def solution(dirs):
    # 규칙 선언
    move = {
        'U': (0, 1),
        'D': (0, -1),
        'L': (-1, 0),
        'R': (1, 0)
    }

    x, y = 0, 0
    routes = set()

    for d in dirs:
        dx, dy = move[d] # move에서 규칙에 맞는 튜플 요소 추출
        nx, ny = x + dx, y + dy # 현재 좌표와 튜플 요소 합산하여 다음 좌표 구하기

        if not (-5 <= nx <= 5 and -5 <= ny <= 5):
            continue

        curr = (x, y) # 현재좌표
        next = (nx, ny) # 다음좌표

        routes.add(tuple(sorted((curr, next))))

        x, y = nx, ny

    return len(routes)