덱을써서 뱀의 길이를 계산한다
꼬리 짧아지면 뒤에서 pop 머리가 앞으로 나아가면 push_front
-소스코드(c++)
#include <iostream>
#include <deque>
using namespace std;
int main()
{
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int applenum, num, selnum, changetime, time = 0, d = 1, nx = 0, ny = 0;
int applex, appley;
char chsel;
deque <pair<int, char>> turn;
deque <pair<int, int>> snake;
snake.push_back({ 0, 0 });
int arr[101][101] = { 0, };
cin >> num;
cin >> applenum;
for (int i = 0; i < applenum; i++)
{
cin >> applex >> appley;
arr[appley - 1][applex - 1] = 1;// 1은 사과
}
cin >> selnum;
for (int i = 0; i < selnum; i++)
{
cin >> changetime >> chsel;
turn.push_back({ changetime,chsel });
}
while (1)
{
nx = nx + dx[d];
ny = ny + dy[d];
time++;
if (nx < 0 || ny < 0 || nx >= num || ny >= num)
{
cout << time;
break;
}
if (!turn.empty())
{
if (turn.front().first == time)
{
char ch;
ch = turn.front().second;
if (ch == 'D')
{
d = (d + 3) % 4;
}
else
{
d = (d + 1) % 4;
}
turn.pop_front();
}
}
//cout <<"ddd" <<d<<"\n ";
if (arr[nx][ny] == 2) // 뱀일 경우
{
//cout << "뱀" < cout << time;
break;
}
else if (arr[nx][ny] == 1) // 사과일 경우
{
arr[nx][ny] = 2;
//cout << "\n사과";
snake.push_front({ nx,ny });
}
else // 그냥 길일경우
{
arr[nx][ny] = 2; // 뱀이다
snake.push_front({ nx,ny });
int x = snake.back().first;
int y = snake.back().second;
//cout << "\nx" << x << "\ny" << y;
if (!snake.empty())
{
snake.pop_back();
arr[x][y] = 0;
}
}
}
}
'Programming > 알고리즘' 카테고리의 다른 글
[프로그래머스] 타겟 넘버 (0) | 2021.03.22 |
---|---|
[프로그래머스] 크레인 인형뽑기 게임 (0) | 2021.03.16 |
[백준][10174]팰린드롬 (0) | 2020.10.17 |
[백준][2577] 숫자의 개수 (0) | 2020.10.17 |
정렬 알고리즘 - 수정 (0) | 2017.11.17 |