[BOJ/C++] 3190(뱀)

푸른별·2023년 8월 15일
0

Algorithm

목록 보기
29/47
post-thumbnail

https://www.acmicpc.net/problem/3190

2. 풀이 과정

  1. 별다른 변화 없이 뱀의 머리와 꼬리의 동향만 살펴주면 됨 -> 시뮬레이션
  2. 왼쪽 및 오른쪽 회전은 즉 4방향 탐색을 의미 -> BFS
  • 문제 난이도 자체는 상당히 낮은 편입니다. 다만 예시 입출력만으로 해결되지 않는다는 전제를 가지고 풀어야하므로 최대한 일반화된 코드를 작성하도록 노력합니다.

  • 이런 긴 문제 풀 때는 solution함수에 주석을 기준으로 꽉꽉 눌러담아야 겠다고 생각하게 되었습니다.(물론 시뮬레이션 + BFS 문제에서 예상하는 것이며, 당연히 필요에 따라 함수를 얼마든지 구현해야 함은 자명합니다.)

3. 정답 코드

#include<iostream>
#include<queue>
using namespace std;
#define p pair<int, int>

int n, k, l, x, dir = 0, answer = 0;
char c;
int area[101][101];
int dx[]{ 0,1,0,-1 };
int dy[]{ 1,0,-1,0 };

void input() {
	cin >> n >> k;
	for (int i = 0;i < k;++i) {
		int a, b;
		cin >> a >> b;
		area[a][b] = 2;
	}
	cin >> l;
}

void solution() {
	input();
	queue<p> time;
	deque<p> snake;
	snake.push_back({ 1, 1 });
	area[1][1] = 1;
	for (int i = 0;i < l;++i) {
		cin >> x >> c;
		time.push({ x,c });
	}
	while (1) {
		++answer;
		int nx = snake.front().first + dx[dir];
		int ny = snake.front().second + dy[dir];
		if (nx < 1 || ny < 1 || nx > n || ny > n || area[nx][ny] == 1) break;
		snake.push_front({ nx,ny });
		if (area[nx][ny] != 2) {
			area[snake.back().first][snake.back().second] = 0;
			snake.pop_back();
		}
		area[nx][ny] = 1;
		if (time.empty()) continue;
		if (answer == time.front().first) {
			if (time.front().second == 'L') dir = (dir + 3) % 4;
			else dir = (dir + 1) % 4;
			time.pop();
		}
	}
	cout << answer;
}

int main() {
	cin.tie(0);  cout.tie(0);
	ios_base::sync_with_stdio(0);
	solution();
	return 0;
}

profile
묵묵히 꾸준하게

0개의 댓글