In [1]:
1
from sys import stdin
14499. 주사위 굴리기
주사위가 줄러가는데로 주어진 조건에 맞는 output을 출력하면 된다. beakjoon problem
Parse Data
In [2]:
1
2
3
4
5
6
7
8
9
10
11
12
stdin = open('data/dice.txt')
input = stdin.readline
n, m, x, y, k = list(map(int, input().split()))
grid = [list(map(int, input().split())) for _ in range(n)]
moves = list(map(int, input().split()))
# print(n, m, x, y, k)
# print(grid)
# print(moves)
right, left, up, down = 1, 2, 3, 4
shift = {up: (-1, 0), down: (1, 0), left: (0, -1), right: (0, 1)}
north, south, west, east, front, back = (-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, 1), (0, 0, -1)
positions = [north, south, west, east, front, back]
Implement Dice Object
주사위를 rotate하는 것을 구현해야한다.
경우의 수를 따져서 구현하는 방법, 연역적으로 구현하는 방법 두가지중 후자를 선택하였다.
In [3]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Dice:
def __init__(self):
self.pos = {direction: 0 for direction in positions}
def __repr__(self):
ans = '\n'.join(['{}: {}'.format(k, v) for k, v in self.pos.items()])
return ans
def rotate(dice:Dice, direction):
def rotateOnce(x, y, z, direction):
if direction == left: return (y, -x, z)
elif direction == right: return (-y, x, z)
elif direction == up: return (z, y, -x)
elif direction == down : return (-z, y, x)
assert "direction is not correct!"
curpos = positions[0]
tmp = dice.pos[curpos]
for _ in range(4):
curpos = rotateOnce(*curpos, direction)
tmp, dice.pos[curpos] = dice.pos[curpos], tmp
sanity check
In [4]:
1
2
3
4
5
6
7
8
dice = Dice()
for i, p in enumerate(positions):
dice.pos[p] = i
print(dice)
rotate(dice, 4)
print('---- after rotate ----')
print(dice)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
(-1, 0, 0): 0
(1, 0, 0): 1
(0, -1, 0): 2
(0, 1, 0): 3
(0, 0, 1): 4
(0, 0, -1): 5
---- after rotate ----
(-1, 0, 0): 4
(1, 0, 0): 5
(0, -1, 0): 2
(0, 1, 0): 3
(0, 0, 1): 1
(0, 0, -1): 0
In [5]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def solution(grid, moves, start):
dice = Dice()
ans = []
x, y = start
for m in moves:
if not (0 <= x + shift[m][0] < len(grid) and 0 <= y + shift[m][1] < len(grid[0])):
continue
rotate(dice, direction=m)
x, y = x + shift[m][0], y + shift[m][1]
if grid[x][y]:
dice.pos[south] = grid[x][y]
grid[x][y] = 0
else:
grid[x][y] = dice.pos[south]
ans.append(dice.pos[north])
return '\n'.join(str(e) for e in ans)
In [6]:
1
print(solution(grid, moves, (x, y)))
1
2
3
4
5
6
7
8
9
0
0
3
0
0
8
6
3
Leave a comment