백준 14499 주사위 굴리기, 파이썬

oong·2022년 9월 6일
0

문제

https://www.acmicpc.net/problem/14499

이 문제는 복잡한 알고리즘이 필요한 문제가 아니라, 구현 & 시뮬레이션이 중점인 문제다.

머릿속으로 주사위를 그려가며 동서남북으로 이동할 때 전개도의 숫자들도 어떻게 이동하는지 생각해보는 것이 중요하다. (연습장 필수인 문제)

주사위의 숫자들은 이동 방향에 따라 저렇게 이동한다.

코드

n, m, x, y, k = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(n)]

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

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

def goDice(r, c, command):
    global x, y
    dr = [1, -1, 0, 0] # 하상우좌 4312
    dc = [0, 0, 1, -1]

    if command == 1:
        nr = r + dr[2]
        nc = c + dc[2]
        if nr < 0 or nr >= n or nc < 0 or nc >= m:
            return
        dice[2], dice[1], dice[3], dice[5] = dice[1], dice[5], dice[2], dice[3]
    elif command == 2:
        nr = r + dr[3]
        nc = c + dc[3]
        if nr < 0 or nr >= n or nc < 0 or nc >= m:
            return
        dice[1], dice[2], dice[3], dice[5] = dice[2], dice[3], dice[5], dice[1]
    elif command == 3:
        nr = r + dr[1]
        nc = c + dc[1]
        if nr < 0 or nr >= n or nc < 0 or nc >= m:
            return
        dice[0], dice[2], dice[4], dice[5] = dice[2], dice[4], dice[5], dice[0]
    else:
        nr = r + dr[0]
        nc = c + dc[0]
        if nr < 0 or nr >= n or nc < 0 or nc >= m:
            return
        dice[0], dice[2], dice[4], dice[5] = dice[5], dice[0], dice[2], dice[4]

    if arr[nr][nc] == 0:
        arr[nr][nc] = dice[5]
    else:
        dice[5] = arr[nr][nc]
        arr[nr][nc] = 0
    x, y = nr, nc
    print(dice[2])

for command in commands:
    goDice(x, y, command)

코드를 더 깔끔하게 작성할 수 있겠지만,,, 전개도 생각하느라 머리를 너무 많이 써서 패스,,,,

주어진 테스트 케이스가 많아서 어느 부분이 틀렸는지 바로 알고, 코드를 수정하면서 문제를 한번에 해결할 수 있었다.

0개의 댓글