JAVA/문제 풀이
[백준 / BOJ] 14499번 : 주사위 굴리기 - JAVA
ahue
2023. 9. 28. 22:29
728x90
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
시뮬레이션
이 문제는 딱히 함정도 없고 주어진 조건에만 충실하게 풀면 답이 나온다.
주사위를 굴려 값이 바뀌는 걸 구현하는 게 가장 귀찮았는데, 위로 굴리기, 아래로 굴리기, 왼쪽으로 굴리기, 오른쪽으로 굴리기 모두 "윗면"과 "아랫면"을 포함해서 바뀐다는 것을 알게 되었다. 따라서 함수를 하나 만들어서 굴리도록 했다.
static void change_dice(int n, int m, int[] dice) {
int tmp = dice[0];
dice[0] = dice[n];
dice[n] = dice[1];
dice[1] = dice[m];
dice[m] = tmp;
}
각 방향마다 n과 m 값만 달라진다.
전체 코드
// 시간 : 84ms
// 메모리 : 11848KB
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int[] dice = {0, 0, 0, 0, 0, 0}; // 위, 아래, 북, 남, 동, 서
int[][] 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());
StringBuilder sb = new StringBuilder();
int[] dr = {0, 0, 0, -1, 1};
int[] dc = {0, 1, -1, 0, 0};
while(K-- > 0) {
int d = Integer.parseInt(st.nextToken());
int nr = r + dr[d];
int nc = c + dc[d];
if(nr >= N || nc >= M || nr < 0 || nc < 0) continue;
if(d == 1) {
change_dice(5, 4, dice);
} else if(d == 2) {
change_dice(4, 5, dice);
} else if(d == 3) {
change_dice(3, 2, dice);
} else {
change_dice(2, 3, dice);
}
if(map[nr][nc] == 0) map[nr][nc] = dice[1];
else {
dice[1] = map[nr][nc];
map[nr][nc] = 0;
}
r = nr;
c = nc;
sb.append(dice[0]).append("\n");
}
System.out.print(sb);
}
static void change_dice(int n, int m, int[] dice) {
int tmp = dice[0];
dice[0] = dice[n];
dice[n] = dice[1];
dice[1] = dice[m];
dice[m] = tmp;
}
}
반응형