C++:: boj 14499 < 주사위 굴리기 >

jahlee·2023년 9월 14일
0
post-thumbnail

주사위를 굴릴때 각 면의 값을 어떻게 저장하고 변화할지에 대해 생각해 보아야하는 문제이다. 본인의 풀이는 단순히 직관적으로 직접 돌려주는 것 처럼 풀이하였다.

#include <iostream>
#include <vector>

using namespace std;

int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};
int main() {
	int n, m, x, y, k;
	cin >> n >> m >> x >> y >> k;
	vector<vector<int> > board(n, vector<int>(m));
	for (int i=0; i<n; i++) {
		for (int j=0; j<m; j++) {
			cin >> board[i][j];
		}
	}
	int dir;
	vector<int> dice_row(2, 0), dice_col(2, 0);
	int top = 0, bottom = 0;
	while (k--) {
		cin >> dir;
		int nx = x + dx[dir-1], ny = y + dy[dir-1];
		if (nx<0 || ny <0 || nx >= n || ny >= m) continue;
		int tmp;
		switch (dir) {
			case 1:// 동
				tmp = dice_row[0];
				dice_row[0] = bottom;
				bottom = dice_row[1];
				dice_row[1] = top;
				top = tmp;
				break;
			case 2:// 서
				tmp = top;
				top = dice_row[1];
				dice_row[1] = bottom;
				bottom = dice_row[0];
				dice_row[0] = tmp;
				break;
			case 3:// 북
				tmp = dice_col[1];
				dice_col[1] = bottom;
				bottom = dice_col[0];
				dice_col[0] = top;
				top = tmp;
				break;
			default:// 남
				tmp = dice_col[0];
				dice_col[0] = bottom;
				bottom = dice_col[1];
				dice_col[1] = top;
				top = tmp;
				break;
		}
		if (!board[nx][ny]) {
			board[nx][ny] = bottom;
		} else {
			bottom = board[nx][ny];
			board[nx][ny] = 0;
		}
		cout << top << "\n";
		x = nx;
		y = ny;
	}
}

주사위를 굴리는 다른 방식의 풀이도 참조한다.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};

/*
  1
3 0 2
  4
  5
*/

void roll(vector<int>& dice, int dir) {
	string order;
	switch (dir) {
		case 1: order = "302";
			break;
		case 2: order = "203";
			break;
		case 3: order = "401";
			break;
		default: order = "104";// 4
			break;
	}
	int tmp = dice[5];
	dice[5] = dice[order[0] - '0'];
	dice[order[0] - '0'] = dice[order[1] - '0'];
	dice[order[1] - '0'] = dice[order[2] - '0'];
	dice[order[2] - '0'] = tmp;
}

int main() {
	int n, m, x, y, k;
	cin >> n >> m >> x >> y >> k;
	vector<vector<int> > board(n, vector<int>(m));
	for (int i=0; i<n; i++) {
		for (int j=0; j<m; j++) {
			cin >> board[i][j];
		}
	}
	int dir;
	vector<int> dice(6, 0);
	while (k--) {
		cin >> dir;
		int nx = x + dx[dir-1], ny = y + dy[dir-1];
		if (nx<0 || ny <0 || nx >= n || ny >= m) continue;
		roll(dice, dir);
		if (!board[nx][ny]) {
			board[nx][ny] = dice[0];
		} else {
			dice[0] = board[nx][ny];
			board[nx][ny] = 0;
		}
		cout << dice[5] << "\n";
		x = nx;
		y = ny;
	}
}

0개의 댓글