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
풀이 방법
구현, 시뮬레이션 문제로 주사위를 굴릴 때의 규칙을 찾는 것이 가장 관건이다. 주사위를 펼친 상태의 그림을 그린 후 동, 서, 남, 북으로 이동하였을 때 각 면의 숫자가 어디로 이동하는 지를 살펴보면 다음과 같다.

동쪽으로 굴린 상태를 보면 3번은 1번, 1번은 4번, 4번은 6번, 6번은 3번의 위치로 바뀐 것을 알 수 있다.
따라서, 방향이 주어졌을 때 위의 이동 규칙에 따라 주사위 면의 숫자를 바꾸어 주면 된다.
코드
import java.io.*;
public class Main {
static int N;
static int M;
static int[][] map;
static int[] dice = new int[7];
static int x, y;
static int[] dx = {0, 0, -1, 1};
static int[] dy = {1, -1, 0, 0};
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
N = Integer.parseInt(line[0]);
M = Integer.parseInt(line[1]);
x = Integer.parseInt(line[2]);
y = Integer.parseInt(line[3]);
int K = Integer.parseInt(line[4]);
map = new int[N][M];
// 지도 입력
for(int i=0; i<N; i++) {
line = br.readLine().split(" ");
for(int j=0; j<M; j++) {
map[i][j] = Integer.parseInt(line[j]);
}
}
line = br.readLine().split(" "); // 명령 입력
// 주사위 굴리기
for(int i=0; i<K; i++) {
rollDice(Integer.parseInt(line[i]));
}
}
public static void rollDice(int d) {
// 이동할 위치
int nx = x + dx[d-1];
int ny = y + dy[d-1];
if(nx < 0 || nx >= N || ny < 0 ||ny >= M) { // 지도의 바깥으로 벗어남
return;
}
x = nx;
y = ny;
if(d == 1) { // 동쪽
int tmp = dice[4];
dice[4] = dice[1];
dice[1] = dice[3];
dice[3] = dice[6];
dice[6] = tmp;
} else if(d == 2) { // 서쪽
int tmp = dice[3];
dice[3] = dice[1];
dice[1] = dice[4];
dice[4] = dice[6];
dice[6] = tmp;
} else if(d == 3) { // 북쪽
int tmp = dice[6];
dice[6] = dice[2];
dice[2] = dice[1];
dice[1] = dice[5];
dice[5] = tmp;
} else { // 남쪽
int tmp = dice[6];
dice[6] = dice[5];
dice[5] = dice[1];
dice[1] = dice[2];
dice[2] = tmp;
}
if(map[nx][ny] == 0) {
map[nx][ny] = dice[6];
} else {
dice[6] = map[nx][ny];
map[nx][ny] = 0;
}
System.out.println(dice[1]); // 상단 면 숫자 출력
}
}'알고리즘 > baekjoon' 카테고리의 다른 글
| 백준 17143 낚시왕 자바(java) (0) | 2024.01.18 |
|---|---|
| 백준 3055 탈출 자바(java) (0) | 2024.01.17 |
| 백준 19238 스타트 택시 자바(java) (1) | 2024.01.15 |
| 백준 15685 드래곤 커브 자바(java) (1) | 2024.01.14 |
| 백준 1189 컴백홈 자바(java) (1) | 2024.01.14 |