보물창고 블로그

백준 알고리즘 14499번 주사위 굴리기 풀이 With Python 본문

알고리즘 풀이/백준 알고리즘

백준 알고리즘 14499번 주사위 굴리기 풀이 With Python

홋 메 2020. 6. 30. 14:10
728x90

문제 링크: https://www.acmicpc.net/problem/14499

 

14499번: 주사위 굴리기

첫째 줄에 지도의 세로 크기 N, 가로 크기 M (1 ≤ N, M ≤ 20), 주사위를 놓은 곳의 좌표 x y(0 ≤ x ≤ N-1, 0 ≤ y ≤ M-1), 그리고 명령의 개수 K (1 ≤ K ≤ 1,000)가 주어진다. 둘째 줄부터 N개의 줄에 지도

www.acmicpc.net

 

문제의 해결은 각 주사위가 동 서 남 북 방향으로 움직였을 때, 주사위에 적혀있는 숫자들을 바 저는 뀌면 된다. 

저는 주사위를 담은 배열을 선언한 뒤에 주사위를 동 서 남 북으로 움직였을 때 숫자를 바꾸는 방식으로 문제를 해결하였습니다. 소스코드는 아래와 같습니다.

from collections import deque


def solution(map1, order, n, m, x, y, k):
    dx = [0, 0, -1, 1]
    dy = [1, -1, 0, 0]
    stack = []
    dice = [0 for _ in range(6)]
    stack.append([x, y])
    if map1[x][y] != 0:
        dice[5] = map1[x][y]
    for _ in range(k):
        direction = order.popleft()
        nx1, ny1 = stack.pop()
        nx = nx1 + dx[direction - 1]
        ny = ny1 + dy[direction - 1]
        if -1 < nx < n and -1 < ny < m:
            pass
        else:
            stack.append([nx1, ny1])
            continue
        if direction == 2:
            temp = dice[0]
            dice[0] = dice[4]
            temp2 = dice[2]
            dice[2] = temp
            temp = dice[5]
            dice[5] = temp2
            dice[4] = temp
        elif direction == 1:
            temp = dice[0]
            dice[0] = dice[2]
            temp2 = dice[4]
            dice[4] = temp
            temp = dice[5]
            dice[5] = temp2
            dice[2] = temp
        elif direction == 3:
            temp = dice[0]
            dice[0] = dice[3]
            temp2 = dice[1]
            dice[1] = temp
            temp = dice[5]
            dice[5] = temp2
            dice[3] = temp
        elif direction == 4:
            temp = dice[0]
            dice[0] = dice[1]
            temp2 = dice[3]
            dice[3] = temp
            temp = dice[5]
            dice[5] = temp2
            dice[1] = temp
        if map1[nx][ny] == 0:
            map1[nx][ny] = dice[5]
        else:
            dice[5] = map1[nx][ny]
            map1[nx][ny] = 0
        print(dice[0])
        stack.append([nx,ny])


n, m, x, y, k = map(int, input().split())
map1 = []
for _ in range(n):
    map1.append(list(map(int, input().split())))
order = deque(map(int, input().split()))
solution(map1, order, n, m, x, y, k)

소스코드에 대한 질문이 있으시면 댓글남겨주시면 답변드리겠습니다. 

Comments