백준 - 주사위 굴리기 2 (23288)

아놀드·2021년 11월 30일
0

백준

목록 보기
66/73

1. 문제 링크

문제 링크

2. 풀이

주사위 굴리기 문제에서 BFS만 추가된 문제입니다.
주사위 전개도를 갱신하는 로직은 같고,
주사위의 현 위치에서 BFS를 통해 점수와 방향을 갱신하면 됩니다.

3. 전체 코드

#include <bits/stdc++.h>

using namespace std;

int n, m, k;
int my[4] = { -1, 0, 1, 0 };
int mx[4] = { 0, 1, 0, -1 };
int board[20][20], visited[20][20];
int dice[7], tmp[7];
queue<pair<int, int>> q, rq;

bool isOut(int y, int x) {
	return y < 0 || y >= n || x < 0 || x >= m;
}

int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> n >> m >> k;

	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> board[i][j];

	for (int i = 1; i <= 6; i++) dice[i] = i;

	int ans = 0;
	int y = 0, x = 0;
	int d = 1;

	while (k--) {
		int ny = y + my[d];
		int nx = x + mx[d];

		if (isOut(ny, nx)) {
			d = (d + 2) % 4;
			ny = y + my[d];
			nx = x + mx[d];
		}

		for (int i = 1; i <= 6; i++) tmp[i] = dice[i];

		switch (d) {
			case 0: {
				dice[1] = tmp[5];
				dice[2] = tmp[1];
				dice[6] = tmp[2];
				dice[5] = tmp[6];
				break;
			}
			case 1: {
				dice[1] = tmp[4];
				dice[6] = tmp[3];
				dice[4] = tmp[6];
				dice[3] = tmp[1];
				break;
			}
			case 2: {
				dice[5] = tmp[1];
				dice[1] = tmp[2];
				dice[2] = tmp[6];
				dice[6] = tmp[5];
				break;
			}
			case 3: {
				dice[4] = tmp[1];
				dice[3] = tmp[6];
				dice[6] = tmp[4];
				dice[1] = tmp[3];
				break;
			}
		}

		y = ny;
		x = nx;
		int B = board[y][x];
		int C = 1;

		q.push({ y, x });
		rq.push({ y, x });
		visited[y][x] = 1;

		while (!q.empty()) {
			int r = q.front().first;
			int c = q.front().second;

			q.pop();

			for (int dir = 0; dir < 4; dir++) {
				int nr = r + my[dir];
				int nc = c + mx[dir];

				if (isOut(nr, nc)) continue;

				if (visited[nr][nc]) continue;

				if (board[nr][nc] != B) continue;

				q.push({ nr, nc });
				rq.push({ nr, nc });
				visited[nr][nc] = 1;
				C++;
			}
		}

		ans += B * C;

		while (!rq.empty()) {
			int r = rq.front().first;
			int c = rq.front().second;

			visited[r][c] = 0;
			rq.pop();
		}

		if (dice[6] > B) {
			d = (d + 1) % 4;
		}
		else if (dice[6] < B) {
			d = (d + 3) % 4;
		}
	}

	cout << ans;

	return 0;
}
profile
함수형 프로그래밍, 자바스크립트에 관심이 많습니다.

0개의 댓글