프로그래머스/LV2

[프로그래머스 Lv2, python]- 방문 길이

chyam_eun 2025. 1. 21. 11:17

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

 

프로그래머스

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

programmers.co.kr

def solution(dirs):
    dic={"U":[0,1],"D":[0,-1],"L":[-1,0],"R":[1,0]}
    x,y=0,0
    stack=[[0,0]]
    cnt=0
    for i in dirs:
        if -5<x<5:
            x+=dic[i][0]
        if -5<y<5:
            y+=dic[i][1]
        for j in range(len(stack)-1):
            if [x,y]==stack[j]:
                if j>0:
                    if stack[j-1]==stack[-1] or stack[-1]==stack[j+1]:
                        cnt+=1
                        break
                else:
                    if stack[-1]==stack[j+1]:
                        cnt+=1
                        break
        if [x,y]!=stack[-1]:
            stack.append([x,y])                  
    return len(stack)-1-cnt

처음 풀이는 위의 코드였다. 테스트 케이스에서 실패가 많이 떴었다.

만약 x가 -5이고 다음이 R이라서 오른쪽으로 한칸 가게된다면 x를 더해주어야하는데 -5는 x를 계산할수 없기때문에 계산되지 못하였다. 그래서 아래의 코드와 같이 수정해주었다.

def solution(dirs):
    dic={"U":[0,1],"D":[0,-1],"L":[-1,0],"R":[1,0]} 
    x,y=0,0 # 캐릭터의 좌표
    stack=[[0,0]] # 좌표 저장해둘곳
    cnt=0 # 몇번 겹치는가
    for i in dirs: 
        if -5<x<5 or (x==5 and dic[i][0]==-1) or (x==-5 and dic[i][0]==1): # x는 -5초과 5미만이고, x가 5일때 -1이거나 x가 -5일때 1이면 x에 더해준다
            x+=dic[i][0]
        if -5<y<5 or (y==5 and dic[i][1]==-1) or (y==-5 and dic[i][1]==1): # 위와같다
            y+=dic[i][1]
        for j in range(len(stack)-1):
            if [x,y]==stack[j]: # 동일한 좌표가 있을때
                if j>0:
                    if stack[j-1]==stack[-1] or stack[-1]==stack[j+1]: # 정방향이나 역방향과 같으면 겹치는것
                        cnt+=1
                        break
                else:
                    if stack[-1]==stack[j+1]:
                        cnt+=1
                        break
        if [x,y]!=stack[-1]: # 마지막과 같지 않으면 추가
            stack.append([x,y])                  
    return len(stack)-1-cnt # 길이에서 0,0과 겹친부분 개수 빼주기