티스토리 뷰
// 알고리즘
1. 시뮬레이션
2. 주사위 정보를 담을 배열 구현
-> 1차원 크기가 6인 배열 구현
3. 주사위 이동
-> 지면에 닿는 위치는 항상 dice[0] 번을 기준으로 함
-> 주사위를 이동시킬 때 마다 주사위 배열의 위치가 변해야 함.
-> up, down, left, right함수(위치 변환 메서드)를 구현해 각각 주사위 위치를 방향에 따라 변경함
4. 1번 이동할 때마다 출력
-> 한번 이동할 때의 방향값에 따라 위치변환 메서드를 실행하고 dice[0]번과 짝인 dice[5]를 출력 함
더보기
import java.util.*;
import java.io.*;
public class 주사위굴리기_14499 {
static int N, M, x, y, K, map[][], arr[], dice[];
static int[] dr = { 0, 0, 0, -1, 1 }; // 우 좌 상 하
static int[] dc = { 0, 1, -1, 0, 0 };
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
map = new int[N][M];
arr = new int[K];
dice = new int[6];
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++) {
arr[i] = Integer.parseInt(st.nextToken());
}
// 알고리즘
cal();
}
private static void cal() {
for (int i = 0; i < arr.length; i++) {
check(arr[i]);
}
}
private static void check(int k) {
int nr = x + dr[k];
int nc = y + dc[k];
if (nr < 0 || nc < 0 || nr >= N || nc >= M)
return;
switch (k) {
case 1:
right();
break;
case 2:
left();
break;
case 3:
up();
break;
case 4:
down();
break;
}
if (map[nr][nc] == 0) {
map[nr][nc] = dice[0];
System.out.println(dice[5]);
}else {
dice[0] = map[nr][nc];
map[nr][nc] = 0;
System.out.println(dice[5]);
}
x= nr;
y= nc;
}
public static void up() {
int[] ndice = dice.clone();
dice[0] = ndice[1];
dice[1] = ndice[5];
dice[2] = ndice[2];
dice[3] = ndice[3];
dice[4] = ndice[0];
dice[5] = ndice[4];
}
public static void down() {
int[] ndice = dice.clone();
dice[0] = ndice[4];
dice[1] = ndice[0];
dice[2] = ndice[2];
dice[3] = ndice[3];
dice[4] = ndice[5];
dice[5] = ndice[1];
}
public static void left() {
int[] ndice = dice.clone();
dice[0] = ndice[3];
dice[1] = ndice[1];
dice[2] = ndice[0];
dice[3] = ndice[5];
dice[4] = ndice[4];
dice[5] = ndice[2];
}
public static void right() {
int[] ndice = dice.clone();
dice[0] = ndice[2];
dice[1] = ndice[1];
dice[2] = ndice[5];
dice[3] = ndice[0];
dice[4] = ndice[4];
dice[5] = ndice[3];
}
}
※ 탐색은 쉬운데 주사위배열을 저장하는 방법에 대해 고민했던 문제 하지만 항상 마주보는 면이 같기 때문에 1차원 배열로 위치만 바꿔서 해결할 수 있겠다는 생각이 들어서 단순하게 구현함. 이 문제는 푸는사람마다 방식이 다를거라고 생각 함. 다른사람의 풀이도 참고해볼 예정(주사위 배열을 관리하는 방법)
'Algorithm' 카테고리의 다른 글
백준_부분 합_1806 (0) | 2021.02.07 |
---|---|
백준_스타트 택시_19238 (0) | 2021.02.06 |
백준_돌 게임_9655 (0) | 2021.01.29 |
백준_2048 (Easy)_12100 (0) | 2021.01.28 |
백준_부분수열의 합_14225 (0) | 2021.01.25 |