Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 구현
- Back tracking
- DFS
- SWEA
- 알고리즘
- Data Structure
- hash table
- Python
- spring boot
- aws
- CSV
- Trie
- GitHub
- django
- gpdb
- Priority Queue
- BFS
- 시뮬레이션
- 코딩테스트
- Linked list
- 코테
- Algorithm
- Vue.js
- boj
- SQL
- programmers
- 모의SW역량테스트
- Bruth Force
- 알고리듬
- JavaScript
Archives
- Today
- Total
hotamul의 개발 이야기
[Algorithm][C++] BOJ 3190 뱀 본문
url: https://www.acmicpc.net/problem/3190
3190번: 뱀
'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임
www.acmicpc.net
풀이 핵심
1. stack + queue 기능을 할 수 있는 자료 구조 구현
- stack의 top 기능을 통해 현재 뱀의 머리를 알 수 있어야 한다.
- pop 기능은 꼬리를 잘라내야한다 (queue의 pop)
2. 방향을 변경할 때 다음과 같이 나머지 연산을 이용한다.
if (DIR[time] != 0) { // 현재 시간에 방향을 변경해야 할 경우
if (DIR[time] == 'L') { // 반 시계 방향으로 방향을 변경할 경우
dir = (dir + 3) % 4;
}
else dir = (dir + 1) % 4; // 시계 방향으로 방향을 변경할 경우
}
3. 사과를 먹었을 때는 pop을 생략하고 (꼬리 자르기 생략), 사과를 먹지 못했을 때는 pop을 해준다.
코드
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int N;
int map[101][101];
int K, L;
char DIR[10001];
struct pos { int r, c; };
pos snake[100 * 100];
int end, start;
void push(int r, int c) {
map[r][c] = -1;
snake[start].r = r, snake[start++].c = c;
}
pos top() { return snake[start - 1]; }
void pop() {
map[snake[end].r][snake[end++].c] = 0;
}
const int dr[] = { 0,1,0,-1 };
const int dc[] = { 1,0,-1,0 };
int Dummy() {
int time = 0, dir = 0;
push(1, 1);
while (1) {
if (DIR[time] != 0) {
if (DIR[time] == 'L') {
dir = (dir + 3) % 4;
}
else dir = (dir + 1) % 4;
}
++time;
pos cur = top();
int nr = cur.r + dr[dir], nc = cur.c + dc[dir];
if (nr < 1 || nr > N || nc < 1 || nc > N) {
break;
}
if (map[nr][nc] == -1) break;
if (map[nr][nc] == 1) {
push(nr, nc);
}
else {
push(nr, nc);
pop();
}
}
return time;
}
int main() {
int ret = 0;
scanf("%d", &N);
scanf("%d", &K);
for (int i = 0; i < K; i++) {
int r, c;
scanf("%d %d", &r, &c);
map[r][c] = 1;
}
scanf("%d", &L);
for (int i = 0; i < L; i++) {
int t;
char c;
scanf("%d %c", &t, &c);
DIR[t] = c;
}
ret = Dummy();
printf("%d", ret);
return 0;
}
아쉬운 점
1. 전형적인 시뮬레이션 / 구현 문제로 어렵지 않게 풀 수 있었다.
2. STL 사용에 익숙해져 있어 deque를 사용하려 했으나 어렵지 않게 구현할 수 있는 자료구조여서 직접 구현했다.
3. 딱히 아쉬운 점이 없는 문제였다.
'myt-algorithm-practice > Samsung SW Certi Adv' 카테고리의 다른 글
[Algorithm][C++] BOJ 14891 톱니바퀴 (0) | 2021.09.19 |
---|---|
[Algorithm][C++] BOJ 14503 로봇 청소기 (0) | 2021.09.15 |
[Algorithm][C++] BOJ 17143 낚시왕 (0) | 2021.09.13 |
[Algorithm][C++] BOJ 2234 성곽 (0) | 2021.09.12 |
[Algorithm][C++] BOJ 17144 미세먼지 안녕! (0) | 2021.09.09 |
Comments