뱀 (3190)

뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다.

쉬웠다. deque, queue를 활용하면 설계도 쉽다.

#include<iostream>
#include<deque>
#include<queue>
using namespace std;

const int MAX_N = 100;

int DX[4] = { 1, 0, -1, 0 };
int DY[4] = { 0, 1, 0, -1 };

int N, K, L;

deque<pair<int, int>> Snake;
bool Apple[MAX_N + 1][MAX_N + 1];
queue<pair<int, char>> Rotation;

bool IsGameOver(int X, int Y)
{
	if (X < 1 || Y < 1 || X > N || Y > N) return true;
	
	for (pair<int, int> Elem : Snake)
	{
		if ((Elem.first == X) && Elem.second == Y) return true;
	}

	return false;
}

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

	cin >> N >> K;
	for (int i = 0; i < K; ++i)
	{
		int Y, X;
		cin >> Y >> X;
		Apple[Y][X] = true;
	}
	cin >> L;
	for (int i = 0; i < L; ++i)
	{
		int X;
		char C;
		cin >> X >> C;
		Rotation.push(make_pair(X, C));
	}

	Snake.push_back(make_pair(1, 1));

	int Time = 0;
	int Direction = 0;
	while (true)
	{
		Time++;
		int HeadX = Snake.back().first;
		int HeadY = Snake.back().second;

		int NextX = HeadX + DX[Direction];
		int NextY = HeadY + DY[Direction];

		if (IsGameOver(NextX, NextY)) break;

		if (Apple[NextY][NextX])
		{
			Snake.push_back(make_pair(NextX, NextY));

			Apple[NextY][NextX] = false;
		}
		else
		{
			Snake.push_back(make_pair(NextX, NextY));
			Snake.pop_front();
		}

		pair<int, char> Rot = Rotation.front();
		if (Rot.first == Time)
		{
			Rotation.pop();
			if (Rot.second == 'D')
			{
				Direction = (Direction + 1) % 4;
			}
			else
			{
				if (Direction == 0) Direction = 4;
				Direction--;
			}
		}
	}

	cout << Time;

	return 0;
}

image.png