곰퓨타의 SW 이야기

[프로그래머스 level2 방문길이] visited 활용하기 본문

TIL/프로그래머스

[프로그래머스 level2 방문길이] visited 활용하기

곰퓨타 2021. 6. 14. 20:07

해결해야하는 문제는 다음과 같았다.

https://programmers.co.kr/learn/courses/30/lessons/49994?language=python3 

 

코딩테스트 연습 - 방문 길이

 

programmers.co.kr

 

 

 

 

코드가 효율적인 것 같지는 않지만, 이러한 아이디어를 바탕으로 작성한 풀이는 다음과 같다.

def check(pos_x,pos_y):
    if pos_x<0 or pos_x>10 or pos_y<0 or pos_y>10 :
        return False
    return True

def solution(dirs):
    count = 0
    visited = []
    pos_x = 5
    pos_y = 5
    
    for dir in dirs :
        new_x, new_y = pos_x, pos_y
        
        if dir == 'U':
            new_x -= 1
        elif dir == 'D':
            new_x += 1
        elif dir == 'R':
            new_y += 1
        else :
            new_y -= 1
            
        if check(new_x,new_y):
            if [[pos_x,pos_y],[new_x,new_y]] not in visited:
                visited.append([[pos_x,pos_y],[new_x,new_y]])
                visited.append([[new_x,new_y],[pos_x,pos_y]])
                count += 1
            pos_x , pos_y = new_x, new_y
                
    return count
Comments