[Gold IV] 뱀 - 3190
성능 요약
메모리: 13916 KB, 시간: 148 ms
분류
자료 구조(data_structures), 덱(deque), 구현(implementation), 큐(queue), 시뮬레이션(simulation)
문제 설명
'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다.
게임은 NxN 정사각 보드위에서 진행되고, 몇몇 칸에는 사과가 놓여져 있다. 보드의 상하좌우 끝에 벽이 있다. 게임이 시작할때 뱀은 맨위 맨좌측에 위치하고 뱀의 길이는 1 이다. 뱀은 처음에 오른쪽을 향한다.
뱀은 매 초마다 이동을 하는데 다음과 같은 규칙을 따른다.
- 먼저 뱀은 몸길이를 늘려 머리를 다음칸에 위치시킨다.
- 만약 이동한 칸에 사과가 있다면, 그 칸에 있던 사과가 없어지고 꼬리는 움직이지 않는다.
- 만약 이동한 칸에 사과가 없다면, 몸길이를 줄여서 꼬리가 위치한 칸을 비워준다. 즉, 몸길이는 변하지 않는다.
사과의 위치와 뱀의 이동경로가 주어질 때 이 게임이 몇 초에 끝나는지 계산하라.
입력
첫째 줄에 보드의 크기 N이 주어진다. (2 ≤ N ≤ 100) 다음 줄에 사과의 개수 K가 주어진다. (0 ≤ K ≤ 100)
다음 K개의 줄에는 사과의 위치가 주어지는데, 첫 번째 정수는 행, 두 번째 정수는 열 위치를 의미한다. 사과의 위치는 모두 다르며, 맨 위 맨 좌측 (1행 1열) 에는 사과가 없다.
다음 줄에는 뱀의 방향 변환 횟수 L 이 주어진다. (1 ≤ L ≤ 100)
다음 L개의 줄에는 뱀의 방향 변환 정보가 주어지는데, 정수 X와 문자 C로 이루어져 있으며. 게임 시작 시간으로부터 X초가 끝난 뒤에 왼쪽(C가 'L') 또는 오른쪽(C가 'D')로 90도 방향을 회전시킨다는 뜻이다. X는 10,000 이하의 양의 정수이며, 방향 전환 정보는 X가 증가하는 순으로 주어진다.
출력
첫째 줄에 게임이 몇 초에 끝나는지 출력한다.
예전에 구현해본 적 있는 snake game이었다.
deque을 사용해서 snake의 head와 tail을 구하였고, 이동하는 과정에 따라 차근차근 구현하였다.
헷갈렸던 점은 자기 자신의 몸에 부딪히는 경우에 head가 먼저 증가하고, 사과의 유무에 따라 tail이 줄어들기 때문에, tail이 줄어들기 전에 head가 증가할 때 그 곳에 tail이 있을 경우에는 부딪힌 경우로 판단해야 한다는 것이다.
처음에는 tail이 모두 줄어든 후에 충돌 여부를 확인해서 테스트케이스 3에서 맞지 않는 실수가 있었다.
그리고 회전은 X초가 끝난 후에 하는 것이기 때문에 while문의 하단에 위치하도록 하였다.
과정은 다음과 같다.
1. 초 증가
2. 머리를 다음칸에 위치
3. 벽에 부딪히는지 확인
4. 자기 자신의 몸에 부딪히는지 확인
5. apple의 존재유무에 따라 꼬리 줄여주기
6. 회전여부 확인
package BOJ.Gold.g4;
import java.util.*;
public class BOJ_3190_뱀 {
static final int APPLE = 2;
static final int SNAKE = 1;
static int[] dr = {0, 1, 0, -1}; // D기준 (오른쪽으로 회전) 오-아-왼-위
static int[] dc = {1, 0, -1, 0}; // 오-아-왼-위
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[][] map = new int[N + 1][N + 1];
int K = sc.nextInt(); // 사과 개수
for (int i = 0; i < K; i++) {
int r = sc.nextInt();
int c = sc.nextInt();
map[r][c] = APPLE; // 사과는 2
}
int L = sc.nextInt(); // 방향 전환
Map<Integer, String> dirMap = new HashMap<>();
for (int i = 0; i < L; i++) {
int sec = sc.nextInt();
String dir = sc.next();
dirMap.put(sec, dir);
}
Deque<int[]> snake = new ArrayDeque<>();
map[1][1] = SNAKE; // 뱀은 1로 표시
snake.offerFirst(new int[]{1, 1});
int sec = 0;
int dir = 0; // 처음 방향은 오른쪽
while (true) {
sec++;
int[] head = snake.peekFirst(); // head
// 머리를 다음칸에 위치
int nr = head[0] + dr[dir];
int nc = head[1] + dc[dir];
if (nr < 1 || nr > N || nc < 1 || nc > N) {
// 벽에 부딪힘
System.out.println(sec);
break;
}
// 머리 옮겨주기
if (map[nr][nc] == 1) {
// 자신의 몸에 부딪힘
System.out.println(sec);
break;
}
// 사과가 있는지 검사
if (map[nr][nc] != APPLE) {
// 사과가 없으면 꼬리 없애기
int[] tail = snake.pollLast();
map[tail[0]][tail[1]] = 0;
}
// 새로운 head 추가
map[nr][nc] = 1;
snake.addFirst(new int[]{nr, nc});
// 회전하는지 확인
if (dirMap.get(sec) != null) {
String rotate = dirMap.get(sec);
if (rotate.equals("L")) {
dir = (4 + dir - 1) % 4;
} else {
dir = (dir + 1) % 4;
}
}
}
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 1107 - 리모컨 (자바 Java) (0) | 2022.12.04 |
---|---|
[백준] 5430 - AC (자바 Java) (1) | 2022.12.04 |
[백준] 2343 - 기타 레슨 (자바 Java) (0) | 2022.12.03 |
[백준] 1654 - 랜선 자르기 (자바 Java) (1) | 2022.12.02 |
[백준] 11437 LCA , 11438 LCA2 (자바 Java) (0) | 2022.12.01 |