[코드트리] 삼성 SW 정육면체 한번 더 굴리기 (파이썬)

dongEon·2024년 4월 19일
0

https://www.codetree.ai/training-field/frequent-problems/problems/cube-rounding-again/description?page=1&pageSize=20

난이도 GOLD III

문제해결 아이디어

  • 주사위를 펼쳐 놓고 row와 col 로 구분한뒤
  • 방향대로 굴렸을 때(상하좌우) row 와 col 의 변경된 부분을 수정하면 굴린 이후의 주사위 모양이 된다

소스코드

import sys
from collections import deque

input = sys.stdin.readline

# 아랫면이 보드 숫자보다 크면 시계방향으로 90도
# 아랫면이 보드 숫자보다 작으면 반시계 방향 90도
# 진행방향으로 이동시 벽에 부딪히면 180도 다시 회전

# 주사위를 펼쳐 놓고 row와 col 로 구분한뒤
# dir로 굴렸을때 row, col를 변경

def count(x, y):
    target = board[x][y]
    visited = [[0] * n for _ in range(n)]
    q = deque([(x, y)])
    visited[x][y] = 1
    cnt = 1
    while q:
        x, y = q.popleft()

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < n and 0 <= ny < n and board[nx][ny] == target and not visited[nx][ny]:
                cnt += 1

                q.append((nx,ny))
                visited[nx][ny] = 1

    return target * cnt

def roll(x, y, dir):
    global total
    nx = x + dx[dir]
    ny = y + dy[dir]

    if nx < 0 or nx >= n or ny < 0 or ny >= n:
        dir -= 2
        dir %= 4
        nx = x + dx[dir]
        ny = y + dy[dir]

    if dir == 0:
        row.rotate(-1)
        col[1] = row[1]
        col[3] = row[3]

    elif dir == 2:
        row.rotate(1)
        col[1] = row[1]
        col[3] = row[3]

    elif dir == 1:
        col.rotate(-1)
        row[1] = col[1]
        row[3] = col[3]

    elif dir == 3:
        col.rotate(1)
        row[1] = col[1]
        row[3] = col[3]

    if row[1] > board[nx][ny]:
        dir += 1
    elif row[1] < board[nx][ny]:
        dir -= 1

    dir %= 4

    total += count(nx, ny)

    return nx, ny, dir

n, m = map(int, input().split())
board = []
for _ in range(n):
    board.append(list(map(int, input().split())))

row, col = deque([4, 6, 3, 1]), deque([5, 6, 2, 1])


total = 0
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, dir = 0, 0, 0  # 우,하,좌,상
for _ in range(m):
    x, y, dir = roll(x, y, dir)

print(total)
profile
반갑습니다! 알고리즘 문제 풀이 정리 블로그 입니다. 피드백은 언제나 환영입니다!

0개의 댓글