본문 바로가기
PROGRAMMERS

[프로그래머스/파이썬] 방문 길이

by kode-daks 2025. 1. 16.

내 풀이

def solution(dirs):
    answer = 0
    cur_location = (0,0) # 현재 위치
    path = set() # 겹치는 것은 제외

	# 현재 위치 & 방향 -> 다음 위치
    def move(current, direction):
        x, y = current
        if direction == "U":
            y += 1
        elif direction == "D":
            y -= 1
        elif direction == "R":
            x += 1
        elif direction == "L":
            x -= 1
        
        if not -5 <= x <=5 or not -5 <= y <= 5: # 범위를 벗어나면 현재에 머물도록
            return current
        return (x,y)
    
    
    for d in dirs:
        next_location = move(cur_location, d)
        if str(cur_location) == str(next_location): # 움직이지 못한 경우는 다음으로
            continue
        # 방향을 무시하기 위해 sorted 사용
        path.add(str(sorted((str(cur_location), str(next_location)))))
        cur_location = next_location # 위치 업데이트

    return len(path) # 경로의 개수

 

메모

set에는 set을 더할 수 없다.