알고리즘

[Lv.2] 프로그래머스 - 방문길이

뚜벅-뚜벅 2021. 6. 23. 19:27

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

 

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

 

programmers.co.kr

[접근]

좌표 개수만큼 2차원 배열을 생성한다

반복문으로 명령어를 확인하고 그에 따라 좌표를 움직인다

visited 집합에 경로가 없으면 경로를 저장한다. (x, y, nx ,ny )

→ 이 때 도착 좌표에서 출발 좌표로 향하는 경로도 같은 경로이므로 거꾸로 온적이 없는지 확인한다.

# if (x,y,nx,ny) not in visited and (nx,ny,x,y) not in visited:

 

해당사항이 없으면 answer +=1 로 처음지나온 경로 값을 늘려준다

 

def solution(dirs):
    visited=set()
    
    game_map = [[0]*11 for _ in range(11)]
    x = 5
    y = 5
    step = 0
    
    for i in range(len(dirs)):
        if dirs[i] == 'U':
            nx = x 
            ny = y - 1
        elif dirs[i] =='L':
            nx = x - 1
            ny = y 
        elif dirs[i] == 'D':
            nx = x 
            ny = y + 1
        elif dirs[i] == 'R':
            nx = x + 1
            ny = y
        if nx <0 or ny <0 or nx>10 or ny>10:
            continue
        if (x,y,nx,ny) not in visited and (nx,ny,x,y) not in visited: #반대를 생각안했네
            visited.add((x,y,nx,ny))
            step +=1
        x = nx
        y = ny
            
    return step