[프로그래머스]/python

[프로그래머스] 코딩테스트연습>연습문제>공원 산책

0_TLS 2024. 1. 19. 18:29

문제 보기

 

<나의 풀이> - 실패(1)

def solution(park, routes):
    for i in range(len(park)):
        for j in range(len(park[i])):
            if park[i][j] == "S":
                x,y = i,j

    d={'E':(0,1), 'W':(0,-1), 'N':(-1,0), 'S':(1,0)}

    for route in routes:
        direction, distance = route.split()
        dx, dy = d[direction] 
        n = int(distance)
        tmp_x, tmp_y = x,y
        
        for _ in range(n):
            nx = tmp_x + dx
            ny = tmp_y + dy
            
            if 0 <= nx <= len(park)-1 and 0 <= ny <= len(park[0])-1 and park[nx][ny] != 'X':
                x,y = nx, ny
                tmp_x, tmp_y = nx, ny
            else:
                pass
                
    return [x,y]

 

 

 

<코드 수정> -정답(2)

def solution(park, routes):
    for i in range(len(park)):
        for j in range(len(park[i])):
            if park[i][j] == "S":
                x,y = i,j

    d={'E':(0,1), 'W':(0,-1), 'N':(-1,0), 'S':(1,0)}

    for route in routes:
        direction, distance = route.split()
        dx, dy = d[direction] 
        n = int(distance)
        tmp_x, tmp_y = x,y
        canmove = True

        for _ in range(n):
            nx = tmp_x + dx
            ny = tmp_y + dy

            if 0 <= nx <= len(park)-1 and 0 <= ny <= len(park[0])-1 and park[nx][ny] != 'X':
                canmove = True
                tmp_x, tmp_y = nx, ny
            else:
                canmove = False
                break
                
        if canmove:
            x,y = nx, ny
            
    return [x,y]

 

 

(1)번 코드는 주어진 명령에서 이동할 칸수를 한번에 이동함. 예를 들어 두칸 중 한칸만 이동 가능하다면 해당 명령을 아예 무시하고 바로 다음 명령을 수행함.

 

(2)번 코드는 주어진 명령에서 이동할 칸수를 한칸씩 이동하기 때문에  두칸 중 한칸만 이동 가능하다면 한칸을 이동하는 명령까지는 수행함.