본문 바로가기

개발/algorithm

[백준 14499번] 주사위 굴리기 - python

문제 링크

풀이 

회전 시 규칙을 찾아 풀어주면 된다. 

dice에 위치별 숫자를 저장한다.

dice[0]은 주사위의 위 

dice[1]은 뒤 

dice[2]은 오른쪽 

dice[3]는 왼쪽 

dice[4]는 앞

dice[5]은 바닥

이라고 설정한다. 

각 값을 a,b,c,d,e,f라고 한다면, 주사위를 오른쪽으로 돌렸을 때 위치는 

a, b, c, d, e, f  -> d, b, a, f, e, c 로 변하게 된다. 이렇게 방향 별 변하는 위치를 찾아주면 된다. 

n, m, x, y, k = map(int,input().split())

graph = []
dice = [0,0,0,0,0,0]

for _ in range(n):
    graph.append(list(map(int,input().split())))
    
dx = [ 0,0,-1,1 ]
dy = [ 1, -1, 0,0]

order = list(map(int,input().split()))

def turn(dir):
    a, b, c, d, e, f = dice[0], dice[1], dice[2], dice[3], dice[4], dice[5]
    # 오른쪽 
    if dir == 0: 
        dice[0], dice[1], dice[2], dice[3], dice[4], dice[5] = d, b, a, f, e, c
    # 왼쪽 
    elif dir == 1: 
        dice[0], dice[1], dice[2], dice[3], dice[4], dice[5] = c, b, f, a, e, d
    # 위쪽 
    elif dir == 2: 
        dice[0], dice[1], dice[2], dice[3], dice[4], dice[5] = e, a, c, d, f, b

    else:
        dice[0], dice[1], dice[2], dice[3], dice[4], dice[5] = b, f, c, d, a, e

nx = x 
ny = y 
for i in range(k):
    d = order[i] -1
    
    nx += dx[d]
    ny += dy[d]

    if 0 > nx or nx >=n or ny <0 or ny >= m:
        nx -= dx[d]
        ny -= dy[d]
        continue 
    
    turn(d)
    if graph[nx][ny] :
        dice[-1] = graph[nx][ny]
        graph[nx][ny] = 0 
    else :
        graph[nx][ny] = dice[-1]
        
    print(dice[0])