본문 바로가기

Algorithm/문제

[백준 / JAVA] 14499. 주사위 굴리기 (G4)

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

 

14499번: 주사위 굴리기

첫째 줄에 지도의 세로 크기 N, 가로 크기 M (1 ≤ N, M ≤ 20), 주사위를 놓은 곳의 좌표 x, y(0 ≤ x ≤ N-1, 0 ≤ y ≤ M-1), 그리고 명령의 개수 K (1 ≤ K ≤ 1,000)가 주어진다. 둘째 줄부터 N개의 줄에 지

www.acmicpc.net

 

주사위의 움직임만 구현하면 참 쉬운 문제이다. 주사위 전개도를 공책에 그리고 동서남북으로 굴렸을 때 숫자가 어떻게 변화하는지 관찰해보자. 가장 귀찮아 보이는 길이 가장 쉬운 길일 수도 있다.

 

몸이 고생하면 머리가 편하다.

 

import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringTokenizer st;
	static StringBuilder sb;

	public static void main(String[] args) throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
		sb = new StringBuilder();
		st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		diceRow = Integer.parseInt(st.nextToken());
		diceCol = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		map = new int[N][M];
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			for (int j = 0; j < M; j++)
				map[i][j] = Integer.parseInt(st.nextToken());
		}
		st = new StringTokenizer(br.readLine());
		for (int i = 0; i < k; i++)
			if (roll(Integer.parseInt(st.nextToken()) - 1))
				sb.append(dice[1][1] + "\n");
		System.out.println(sb);
	}

	static int N, M, diceRow, diceCol, map[][], dice[][] = { { -1, 0, -1 }, { 0, 0, 0 }, { -1, 0, -1 }, { -1, 0, -1 } },
			dr[] = { 0, 0, -1, 1 }, dc[] = { 1, -1, 0, 0 };

	static boolean roll(int dir) {
		int nr = diceRow + dr[dir];
		int nc = diceCol + dc[dir];
		if (nr < 0 || nc < 0 || nr >= N || nc >= M) // 지도 밖
			return false;
		diceRow = nr;
		diceCol = nc;
		int top = dice[1][1];
		switch (dir) {
		case 0: // 동
			dice[1][1] = dice[1][0];
			dice[1][0] = dice[3][1];
			dice[3][1] = dice[1][2];
			dice[1][2] = top;
			break;
		case 1: // 서
			dice[1][1] = dice[1][2];
			dice[1][2] = dice[3][1];
			dice[3][1] = dice[1][0];
			dice[1][0] = top;
			break;
		case 2: // 북
			dice[1][1] = dice[2][1];
			dice[2][1] = dice[3][1];
			dice[3][1] = dice[0][1];
			dice[0][1] = top;
			break;
		case 3: // 남
			dice[1][1] = dice[0][1];
			dice[0][1] = dice[3][1];
			dice[3][1] = dice[2][1];
			dice[2][1] = top;
			break;
		}
		if (map[diceRow][diceCol] == 0)
			map[diceRow][diceCol] = dice[3][1];
		else {
			dice[3][1] = map[diceRow][diceCol];
			map[diceRow][diceCol] = 0;
		}
		return true;
	}
}