[코드트리] 정육면체 한번 더 굴리기

ewillwin·2024년 10월 7일
0

Problem Solving (CodeTree)

목록 보기
15/16

import sys
from collections import deque
input = sys.stdin.readline

dx = (0, 1, 0, -1) #우하좌상
dy = (1, 0, -1, 0)

N, M = map(int, input().split())
board = [list(map(int, input().split())) for n in range(N)]
dice = [1, 6, 2, 5, 3, 4] # 위 아래 앞 뒤 오 왼

def MoveDice(direction):
    global dice
    a, b, c, d, e, f = dice
    if direction == 0: # 우: 위->오, 오->아래, 아래->왼, 왼->위
        dice = [f, e, c, d, a, b]
    elif direction == 1: # 하: 위->앞, 앞->아래, 아래->뒤, 뒤->위
        dice = [d, c, a, b, e, f]
    elif direction == 2: # 좌: 위->왼, 왼->아래, 아래->오, 오->위
        dice = [e, f, c, d, b, a]
    elif direction == 3: # 상: 위->뒤, 뒤->아래, 아래->앞, 앞->위
        dice = [c, d, b, a, e, f]

def bfs(x, y, number):
    global ans
    queue = deque([]); queue.append((x, y))
    visit = [[False]*N for n in range(N)]; visit[x][y] = True
    while queue:
        x, y = queue.popleft()
        ans += number
        for i in range(4):
            nx, ny = x+dx[i], y+dy[i]
            if 0<=nx<N and 0<=ny<N:
                if not visit[nx][ny] and board[nx][ny] == number:
                    queue.append((nx, ny))
                    visit[nx][ny] = True

direction = 0
ans = 0
x, y = 0, 0
for m in range(M):
    ##### 주사위 굴리기
    nx, ny = x+dx[direction], y+dy[direction]
    if nx < 0 or nx >= N or ny < 0 or ny >= N: direction = (direction+2)%4
    x += dx[direction]; y += dy[direction]
    MoveDice(direction)

    ##### 점수 얻기
    bfs(x, y, board[x][y])

    ##### 진행 방향 결정
    if board[x][y] < dice[1]: direction = (direction+1)%4
    elif board[x][y] > dice[1]: direction = (direction-1)%4

print(ans)
profile
💼 Software Engineer @ LG Electronics | 🎓 SungKyunKwan Univ. CSE

0개의 댓글