본문 바로가기
백준 삼성

[python] 23288 - 주사위 굴리기 2

by 다데기 2022. 8. 26.

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

 

23288번: 주사위 굴리기 2

크기가 N×M인 지도가 존재한다. 지도의 오른쪽은 동쪽, 위쪽은 북쪽이다. 지도의 좌표는 (r, c)로 나타내며, r는 북쪽으로부터 떨어진 칸의 개수, c는 서쪽으로부터 떨어진 칸의 개수이다. 가장 왼

www.acmicpc.net

 

정답률 66.080%

난이도 골3

미리 스코어 다 계산해놓는게 시간 절약(주사위 굴릴때마다 계산하기엔 너무 오래걸림)

 


코드 설명

1. 입력 받기

2. 스코어 보드 생성 (미리 그 자리의 스코어 다 계산해놓기)

3. 주사위 굴리기

 

 

※ 주의할 점

  • 재귀 dfs 쓸때는 재귀초과 주의
  • 밖으로 나갈 시 반대 방향으로

 

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

def move_dice(d):
    if d == 0:
        return [dice[3], dice[1], dice[0], dice[5], dice[4], dice[2]]
    elif d == 1:
        return [dice[1], dice[5], dice[2], dice[3], dice[0], dice[4]]
    elif d == 2:
        return [dice[2], dice[1], dice[5], dice[0], dice[4], dice[3]]
    else:
        return [dice[4], dice[0], dice[2], dice[3], dice[5], dice[1]]


def dfs(x, y, val):
    global cnt
    if (x, y) in group:
        return
    if board[x][y] == val:
        group.append((x, y))
        cnt += 1
        if x > 0:
            dfs(x - 1, y, val)
        if x < n - 1:
            dfs(x + 1, y, val)
        if y > 0:
            dfs(x, y - 1, val)
        if y < m - 1:
            dfs(x, y + 1, val)
    return


# 1. 입력 받기
n, m, k = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
dice = [1, 2, 3, 4, 5, 6]
x, y, d = 0, 0, 0
score = 0

# 2. 스코어 보드 생성 (미리 그 자리의 스코어 다 계산해놓기)
s_board = [[0] * m for _ in range(n)]
for i in range(n):
    for j in range(m):
        if s_board[i][j]:
            continue
        group = []
        cnt = 0
        now = board[i][j]
        dfs(i, j, now)
        for tx, ty in group:
            s_board[tx][ty] = cnt * now


# 3. 주사위 굴리기
for i in range(k):
    nx, ny = x + dx[d], y + dy[d]
    if not (0 <= nx < n and 0 <= ny < m):
        d = (d + 2) % 4
        nx, ny = x + dx[d], y + dy[d]
    val = board[nx][ny]
    score += s_board[nx][ny]
    dice = move_dice(d)

    if dice[5] > val:
        d = (d + 1) % 4
    elif dice[5] < val:
        d = (d - 1) % 4

    x, y = nx, ny

print(score)

코드 결과