[백준] 3190번 뱀 (C++, 삼성 기출)

0

swea

목록 보기
1/10

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

처음으로 도전한 삼성 기출문제이다.
이 문제는 구현에 집중해서 쉽게 풀렸다.
사과에 대한 정보는 미리 board에 넣어두고, 방향 전환에 대한 정보만 queue로 관리해줬다.

1. 현재 진행 방향을 vector의 첫번째 x, y값에 더해 nx, ny를 구해준다.
2. nx, ny가 외각에 닿거나, 자기 몸을 만나면 (board[ny][nx] == 2) break해준다.
3. 문제가 없으면, nx, ny를 vector에 첫번째에 넣는다.
4. nx, ny에 사과가 없으면 board에서 vector의 마지막 x, y 값에 해당하는 자리에 0을 넣어 초기화 해준다.
5. board의 nx, ny에 해당하는 값에 2를 넣어 뱀이 있다는 것을 저장해준다.
6. queue에 원소가 있으면 time과 비교한 뒤에 방향을 전환해준다.

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

int n, k, l;
int b[101][101];
int a[101];
queue<pair<int, char>> d;
vector<pair<int, int>> s;

void change_dir(int& x, int& y, char d) {
	if (x == 1 && y == 0) {
		if (d == 'D') {
			x = 0; y = 1;
		}
		else {
			x = 0; y = -1;
		}
	}
	else if (x == -1 && y == 0) {
		if (d == 'D') {
			x = 0; y = -1;
		}
		else {
			x = 0; y = 1;
		}
	}
	else if (x == 0 && y == 1) {
		if (d == 'D') {
			x = -1; y = 0;
		}
		else {
			x = 1; y = 0;
		}
	}
	else if (x == 0 && y == -1) {
		if (d == 'D') {
			x = 1; y = 0;
		}
		else {
			x = -1; y = 0;
		}
	}
}

int main() {
	cin >> n >> k;
	for (int i = 0; i < k; i++) {
		int x, y;
		cin >> y >> x;
		b[y - 1][x - 1] = 1;
	}
	cin >> l;
	for (int i = 0; i < l; i++) {
		int x; char c;
		cin >> x >> c;
		d.push({ x, c });
	}
	s.push_back({ 0,0 });
	int x_p = 1;
	int y_p = 0;
	int time = 0;
	while (1) {
		time++;
		int nx = s.front().first + x_p;
		int ny = s.front().second + y_p;

		if (ny >= n || ny < 0 || nx >= n || nx < 0) break;
		if (b[ny][nx] == 2) break;

		s.insert(s.begin(), { nx, ny });
		if (b[ny][nx] != 1) {
			int tx = s.back().first;
			int ty = s.back().second;
			b[ty][tx] = 0;
			s.erase(s.begin() + s.size() - 1);
		}
		b[ny][nx] = 2;

		if (!d.empty()) {
			if (d.front().first == time) {
				change_dir(x_p, y_p, d.front().second);
				d.pop();
			}
		}
	}
	cout << time;
}

0개의 댓글