주사위 굴리기


백준 [14499] 주사위 굴리기

문제보기
Alt text

풀이

  • 시뮬레이션

소스코드

import java.util.Scanner;

public class Main {
	static int N, M, K;
	static int[] dice, command;
	static int[][] map;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		int x = sc.nextInt();
		int y = sc.nextInt();
		K = sc.nextInt();
		map = new int[N][M];
		dice = new int[6];
		command = new int[K];

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				map[i][j] = sc.nextInt();
			}
		}

		for (int i = 0; i < K; i++) {
			command[i] = sc.nextInt();
		}
		move(x, y);
	}

	//   1
	// 3 0 2
	//   4
	//   5
	public static void move(int x, int y) {
		int r = x;
		int c = y;
		int[] newDice = dice.clone();

		for (int i = 0; i < K; i++) {
			if (command[i] == 1) { // 동
				int chkC = c + 1;
				if (!isRange(r, chkC))
					continue;
				c = chkC;
				if (map[r][c] == 0) {
					map[r][c] = dice[2];
				} else {
					dice[2] = map[r][c];
					map[r][c] = 0;
				}
				newDice[0] = dice[3];
				newDice[2] = dice[0];
				newDice[3] = dice[5];
				newDice[5] = dice[2];
			} else if (command[i] == 2) { // 서
				int chkC = c - 1;
				if (!isRange(r, chkC))
					continue;
				c = chkC;
				if (map[r][c] == 0) {
					map[r][c] = dice[3];
				} else {
					dice[3] = map[r][c];
					map[r][c] = 0;
				}
				newDice[0] = dice[2];
				newDice[2] = dice[5];
				newDice[3] = dice[0];
				newDice[5] = dice[3];
			} else if (command[i] == 3) { // 북
				int chkR = r - 1;
				if (!isRange(chkR, c))
					continue;
				r = chkR;
				if (map[r][c] == 0) {
					map[r][c] = dice[1];
				} else {
					dice[1] = map[r][c];
					map[r][c] = 0;
				}
				newDice[0] = dice[4];
				newDice[1] = dice[0];
				newDice[4] = dice[5];
				newDice[5] = dice[1];
			} else if (command[i] == 4) { // 남
				int chkR = r + 1;
				if (!isRange(chkR, c))
					continue;
				r = chkR;
				if (map[r][c] == 0) {
					map[r][c] = dice[4]; 
				} else {
					dice[4] = map[r][c];
					map[r][c] = 0;
				}
				newDice[0] = dice[1];
				newDice[1] = dice[5];
				newDice[4] = dice[0];
				newDice[5] = dice[4];
			}
			dice = newDice.clone();
			System.out.println(dice[0]);
		}
	}

	public static boolean isRange(int r, int c) {
		return r >= 0 && c >= 0 && r < N && c < M;
	}
}