백준 - 주사위 굴리기 / Gold 4 / 14499번 / Python

Young Hun Park·2023년 2월 20일
0

문제 📋

백준 - 주사위 굴리기

풀이 📝

import sys

n, m, row, col, k = map(int, sys.stdin.readline().split())
table = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
cmds = list(map(int, sys.stdin.readline().split()))


class Dice:
    def __init__(self, up, down, left, right, top, bottom):
        self.up = up
        self.down = down
        self.left = left
        self.right = right
        self.top = top
        self.bottom = bottom

    def move(self, way):
        if way == 1:
            self.move_right()
        elif way == 2:
            self.move_left()
        elif way == 3:
            self.move_up()
        else:
            self.move_down()

    def move_up(self):
        temp_top = self.top
        self.top = self.down
        self.down = self.bottom
        self.bottom = self.up
        self.up = temp_top

    def move_down(self):
        temp_top = self.top
        self.top = self.up
        self.up = self.bottom
        self.bottom = self.down
        self.down = temp_top

    def move_left(self):
        temp_top = self.top
        self.top = self.right
        self.right = self.bottom
        self.bottom = self.left
        self.left = temp_top

    def move_right(self):
        temp_top = self.top
        self.top = self.left
        self.left = self.bottom
        self.bottom = self.right
        self.right = temp_top


def solution(n, m, row, col, k, table, cmds):
    dice = Dice(0, 0, 0, 0, 0, 0)
    delta_row = [0, 0, -1, 1]
    delta_col = [1, -1, 0, 0]

    for cmd in cmds:
        new_row = row + delta_row[cmd-1]
        new_col = col + delta_col[cmd-1]

        if 0 <= new_row < n and 0 <= new_col < m:
            row = new_row
            col = new_col

            dice.move(cmd)

            if table[row][col] == 0:
                table[row][col] = dice.bottom
            else:
                dice.bottom = table[row][col]
                table[row][col] = 0

            print(dice.top)


solution(n, m, row, col, k, table, cmds)

SW 마에스트로 해외연수 때 구글 엔지니어이신 케빈님과
코딩 인터뷰를 진행 했었는데 단순히 알고리즘을 푸는 것보다
코드를 객체지향 패러다임에 맞춰 잘 구조화 시키는 것도 평가요소라고 하셨다.
따라서 이번 풀이는 최대한 고민하면서 코드를 구조화 시키려 노력했다.

이번 문제는 2차원 지도에서 주사위를 이동시키는 문제이며
주사위가 굴러가는 것만 잘 구현하면 되는 간단한 구현문제였다.

먼저 주사위를 객체화 시켰다.
주사위는 각 면의 값들을 멤버변수로 갖는다. - (top, bottom, up, down, left, right)
그리고 주사위 클래스에 상하좌우로 움직일 수 있는 함수들을 정의 해주었으며
move() 함수를 통해 각각의 방향도 맵핑 시켜주었다.

이렇게 구현하고나니 알고리즘이 들어가는 solution() 함수를
굉장히 깔끔하고 쉽게 구현 할 수 있었다.

비록 코드 전체 길이는 길어졌지만
객체지향설계에서는 캡슐화 원칙에 따라 Dice 클래스는 별도의 파일로 존재할 것이고
개발자는 Dice의 코드를 알 필요가 없다.
즉, solution() 함수 내부의 코드가 더 Clean Code에 가까워졌다고 생각한다.

profile
개발자에게 유용한 지식

0개의 댓글