[Baekjoon] 3190번 뱀.cpp

세동네·2022년 6월 30일
0
post-thumbnail

[백준] 3190번 뱀 문제 링크

이걸 만들면 된다. 이 문제에서 주의할 점은 다음과 같다.

  1. 모든 입력은 미리 받는다.
  2. 꼬리가 사라지는 것보다 머리가 움직이는 게 먼저다.

이것만 잘 숙지한다면 쉽게 해결할 수 있는 문제다. 필자는 뱀의 몸이 맵의 어디에 위치했는지 큐로 만들어 관리했다. 이동할 때 큐에 추가하며 맵에 표시해주고, 이동한 위치에 사과가 없다면 큐에서 원소를 제거하며 맵에서 다시 이동 가능한 길로 표시해주었다.

몸을 만나든 벽을 만나든 게임이 종료돼야 하므로 몸과 벽을 똑같이 취급해주었다.

코드 전문은 아래와 같다.

#include <iostream>
#include <queue>
#define L 1
#define D 3

std::queue<std::pair<int, int>> snake;
int turn[10001] = { 0, };
std::pair<int, int> direction[4] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };
int map[102][102] = { 0, };

int n;

int headRow, headCol, headDir;

int playTime;

bool move() {
	headRow += direction[headDir].first;
	headCol += direction[headDir].second;

	if (map[headRow][headCol] == 1) {
		return true;
	}

	if (map[headRow][headCol] != 2) {

		map[snake.front().first][snake.front().second] = 0;
		snake.pop();
	}
	map[headRow][headCol] = 1;
	snake.push({ headRow, headCol });

	return false;
}

void init() {
	headRow = 1;
	headCol = 1;
	headDir = 3;

	map[headRow][headCol] = 1;
	snake.push({ headRow, headCol });

	playTime = 0;

	for (int index = 0; index <= n + 1; index++) {
		map[index][0] = 1;
	}
	for (int index = 0; index <= n + 1; index++) {
		map[index][n + 1] = 1;
	}
	for (int index = 0; index <= n + 1; index++) {
		map[0][index] = 1;
	}
	for (int index = 0; index <= n + 1; index++) {
		map[n + 1][index] = 1;
	}
}

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	std::cin >> n;

	init();

	int appleNum;
	std::cin >> appleNum;

	int appleRow, appleCol;
	for (int count = 0; count < appleNum; count++) {
		std::cin >> appleRow >> appleCol;

		map[appleRow][appleCol] = 2;
	}

	int turnCnt;
	std::cin >> turnCnt;

	int nextTime;
	char nextDir;

	bool gameOver = false;
	for (; turnCnt > 0; turnCnt--) {
		std::cin >> nextTime >> nextDir;
		if (nextDir == 'L') {
			turn[nextTime] = L;
		}
		else if (nextDir == 'D') {
			turn[nextTime] = D;
		}
	}

	while (!gameOver) {
		gameOver = move();

		if (turn[++playTime] != 0) {
			headDir = (headDir + turn[playTime]) % 4;
		}
	}

	std::cout << playTime;

	return 0;
}

0개의 댓글