대외교육/코딩테스트

[프로그래머스 특강]1-2. 시뮬레이션 예시 : 청소 로봇(기본)

흑요석s 2023. 8. 25. 13:51

1번방법

def solution(moves):
    r,c =0, 0
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    dir = ['U', 'R', 'D', 'L']
    for command in moves: #move문자열 갯수만큼
        for k in range(4):  #4방향
            if command == dir[k]: #k의 방향
                r = r + dr[k]
                c = c + dc[k]
    return [r,c]
                            
print(solution('RRRDDDLU'))
#print(solution('DDDRRRDDLL'))
#print(solution('RRRRRRDDDDDDUULLL'))
#print(solution('RRRRDDDRRDDLLUU'))

 

2번방법

def solution(moves):
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    dir = {'U' : 0, 'R' : 1, 'D':2, 'L':3 }
    r, c = 0,0
    for command in moves:
        #1.command를 가져와서 2.dir의 key를 불러오고 3.그에 대한 value 값을 불러와 더한다 
        r = r + dr[dir[command]] 
        c = c + dc[dir[command]]

    return [r, c]

print(solution('RRRDDDLU'))

 

def solution(n,moves):
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    dir = {'U':0, 'R':1, 'D':2, 'L':3}
    r,c = 0,0
    for command in moves :
        #아직 움직이지 않음.
        nr = r+dr[dir[command]]
        nc = c+dc[dir[command]]
        if nr < 0 or nr >= n or nc < 0 or nc >=n:
            continue #격자 밖 무시 코드

        #움직임
        r = nr
        c = nc
    return [r, c]

print(solution(5,'RRRDDDUUUUUUL'))
print(solution(7,'DDDRRRDDLL'))
print(solution(5,'RRRRRDDDDDU'))
print(solution(6,'RRRRDDDRRDDLLUU'))

 

def solution(moves):
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    dir = {'U':0, 'R':1, 'D':2, 'L':3}
    see = 1   # 보는방향 (12시부터 시계 방향 1,2,3,4)
    r,c = 0,0

    for command in moves :
        if command == 'G' : #전진
            r += dr[see]
            c += dc[see] 

        elif dir[command] == 1 : #방향 전환 1(시계)
            see = (see + 1) % 4
        else :
            see = (see + 3) % 4  
            #방향전환 2(반시계)  see - 1 과 동일하다보면됨
            # -90도는 270도를 회전한 것과 같음.
        

    return [r,c]

print(solution('GGGRGGG'))