• 문제 링크
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
• 풀이 과정
주사위의 이동을 지도에 범위에 맞게 이동하도록 지정하고
주사위의 6면에 대응하는 배열을 생성해 그 움직임을 구현한다.
주사위에 각 면을 배열의 인덱스로 표현하면 다음과 같다.
1 | ||
3 | 0 | 2 |
4 | ||
5 |
이동 방향에 따라 각 주사위 면에 지정된 수가 초기값 0에서 변화하는데,
동쪽은 0, 3, 5, 2 서쪽은 0, 2, 5, 3 남쪽은 0, 4, 5, 1 북쪽은 0, 1, 5, 4 의 순서대로 순환하는 규칙에 따라
주사위의 각 면에 지정된 수의 상태 변화를 배열에 갱신한다.
그리고 지도와 주사위가 맞닿을 때 지도의 값이 0 일 시 주사위의 값을 복사해오고
지도의 값이 0이 아닐 시 해당 지도의 값을 주사위에 복사하고 지도의 값은 0으로 바꾸는 로직까지 구현한다.
최종적으로 주사위가 움직인 후 주사위 상단의 값을 반환하여 정답이 출력된다.
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
static int n, m, y, x;
static int[][] map;
static int[] dice = new int[6];
static int[] dy = { 0, 0, -1, 1 };
static int[] dx = { 1, -1, 0, 0 };
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
x = 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++) {
int dir = Integer.parseInt(st.nextToken()) - 1;
y += dy[dir];
x += dx[dir];
if (y < 0 || x < 0 || y >= n || x >= m) {
y -= dy[dir];
x -= dx[dir];
continue;
}
bw.write(move(dir + 1, y, x) + "\n");
}
bw.flush();
}
private static int move(int dir, int y, int x) {
int tmp = dice[0];
switch (dir) {
case 1:
dice[0] = dice[3];
dice[3] = dice[5];
dice[5] = dice[2];
dice[2] = tmp;
break;
case 2:
dice[0] = dice[2];
dice[2] = dice[5];
dice[5] = dice[3];
dice[3] = tmp;
break;
case 3:
dice[0] = dice[1];
dice[1] = dice[5];
dice[5] = dice[4];
dice[4] = tmp;
break;
case 4:
dice[0] = dice[4];
dice[4] = dice[5];
dice[5] = dice[1];
dice[1] = tmp;
break;
}
if (map[y][x] == 0)
map[y][x] = dice[5];
else {
dice[5] = map[y][x];
map[y][x] = 0;
}
return dice[0];
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 14503 로봇 청소기 - Implementation / Java (0) | 2022.06.25 |
---|---|
[백준] 16113 시그널 - Implementation / Java (0) | 2022.06.24 |
[백준] 16506 CPU - Implementation / Java (0) | 2022.06.22 |
[백준] 14500 테트로미노 - Implementation / Java (0) | 2022.06.21 |
[백준] 1966 프린터 큐 - Data Structure / Java (0) | 2022.06.20 |
댓글