2. 알고리즘사이트/1. 백준
뱀 [백준 3190][실버1][Java]
isaacToast
2020. 3. 2. 18:12
반응형
[광고 누르면 오늘의 행운 상승!!]
https://www.acmicpc.net/problem/3190
3190번: 뱀
문제 'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임은 NxN 정사각 보드위에서 진행되고, 몇몇 칸에는 사과가 놓여져 있다. 보드의 상하좌우 끝에 벽이 있다. 게임이 시작할때 뱀은 맨위 맨좌측에 위치하고 뱀의 길이는 1 이다. 뱀은 처음에 오른쪽을 향한다. 뱀은 매 초마다 이동을 하는데 다음과 같은 규칙을 따
www.acmicpc.net
시뮬레이션 문제
Deque를 사용하여 머리와 꼬리의 위치를 바꿔주었다.
import java.io.*;
import java.util.*;
class Position {
int row, col;
Position(int row, int col) {
this.row = row;
this.col = col;
}
}
public class Main {
public static int[] dx = { -1, 0, 1, 0 };
public static int[] dy = { 0, 1, 0, -1 };
public static int dir = 1;
public static int tcnt;
public static int snakemap[][];
public static void main(String[] args) throws Exception {
Deque<Position> snake = new ArrayDeque<Position>();
Position pos = new Position(0, 0);
snake.add(pos); // 삽입
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int map[][] = new int[N][N];
for (int i = 0; i < K; i++) {
int row = sc.nextInt() - 1;
int col = sc.nextInt() - 1;
map[row][col] = 1;
}
int L = sc.nextInt();
int time[] = new int[L];
char ch[] = new char[L];
for (int i = 0; i < L; i++) {
time[i] = sc.nextInt();
ch[i] = sc.next().charAt(0);
}
int cnt = 0;
while (true) {
if(cnt != L) {
if (tcnt - time[cnt] == 0) {
if (ch[cnt] == 'L') dir = (dir + 3) % 4;
else if (ch[cnt] == 'D') dir = (dir + 1) % 4;
cnt++;
}
}
tcnt++;
int nx = snake.peek().row + dx[dir];
int ny = snake.peek().col + dy[dir];
if (nx < 0 || nx >= N || ny < 0 || ny >= N) {
System.out.println(tcnt); // 선을 넘었다.
return;
}
Position head = new Position(nx, ny);
snake.push(head); // 머리 삽입
head = snake.pop(); //머리를 빼내기
for (int m = 0; m < snake.size(); m++) {
Position p = snake.pop(); // 머리 바로 다음부터 빼기
if (p.row == head.row && p.col == head.col) {
System.out.println(tcnt); // 갈곳에 자기 몸이 있다.
return;
}
snake.add(p); // 꼬리에 넣기
}
snake.push(head); // 머리에 넣기
if (map[nx][ny] == 1) { // 사과일때
map[nx][ny] = 0; //사과삭제
}else {
Position p = snake.pollLast(); // 꼬리를 빼낸다.
}
}
}
}
반응형