3190번: 뱀
'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임
www.acmicpc.net
문제
문제에서 요구하는걸 그대로 구현하는 문제
조건
벽 또는 자기자신 몸과 부딪히면 게임이 끝난다 -> hit(현재row좌표,col좌표, 뱀의좌표 리스트 ) 메소드
뱀의 이동
몸길이를 늘려 머리를 다음칸에 위치한다
이동한 칸에 사과가 있다면 사과가 없어지고 꼬리는 움직이지않는다. -> boolean isapple 로 사과인경우, 아닌경우 체크
이동한칸에 사과가 없다면 몸길이를 줄여 꼬리가 위치한 칸을 비운다.
package study.week8;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class BJ뱀 {
/*
* BJ뱀 -
*/
static int N, K, L;
static int[][] map;
static int[][] cmds;
static int dir;
static int[] dr = { -1, 0, 1, 0 };
static int[] dc = { 0, 1, 0, -1 };
static List<Point> snake;
static boolean[][] v;
public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("input/뱀.txt"));
Scanner sc = new Scanner(System.in);
snake = new LinkedList<>();
N = sc.nextInt();// 배열의크기
map = new int[N + 2][N + 2];
v = new boolean[N + 2][N + 2];
K = sc.nextInt();// 사과의갯수
// 사과의 위치는 2로 표시
for (int i = 0; i < K; i++) {
map[sc.nextInt()][sc.nextInt()] = 2;
} // end for
L = sc.nextInt();
cmds = new int[L][2]; // 시간이랑 왼쪽오른쪽 명령 저장할 배열
for (int i = 0; i < L; i++) {
cmds[i][0] = sc.nextInt();
char temp = sc.next().charAt(0);
// 왼쪽 1 오른쪾 2
int input = (temp == 'L') ? 1 : 2;
cmds[i][1] = input;
} // end for
dir = 1; // 처음에 오른쪽을 봄
// 좌표, 방향 넘겨주면서 move하는데 cnt를 반환한다
System.out.println(move(1, 1));
}
static int move(int r, int c) {
// 뱀을 담을 리스트
snake.add(new Point(r, c));
int time = 0;
int nr = r, nc = c;
boolean isapple=false;
while (true) {
// 시간체크해서 방향 바꾸기
timecheck(time);
nr += dr[dir];
nc += dc[dir];
time++;
isapple=false;
// 경계체크
if (nr < 1 || nr > N || nc < 1 || nc > N)
return time;
// 내몸이랑 부딪히는지 체크
if (hit(snake, nr, nc))
return time;
// 사과인지, 사과이면 전진만 하고 리스트삭제안함
if (map[nr][nc] == 2) {
isapple = true;
map[nr][nc]=0;
snake.add(new Point(nr, nc));
}
// 아니면 한칸전진하고 리스트삭제
if(!isapple) {
snake.add(new Point(nr, nc));
snake.remove(0);
}
}
}
private static void timecheck(int time) {
for (int i = 0; i < L; i++) {
if (cmds[i][0] == time) {
// 왼쪽인지 오른쪽인지 확인
dir = (cmds[i][1] == 1) ? (dir - 1 + 4) % 4 : (dir + 1 + 4) % 4;
}
}
}
// 내몸이랑 부딪히는지 확인
static boolean hit(List<Point> list, int nr, int nc) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).row == nr && list.get(i).col == nc)
return true;
}
return false;
}
static void print() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
}
static class Point {
int row, col;
public Point(int row, int col) {
super();
this.row = row;
this.col = col;
}
}
}
'Problem Solving > BOJ' 카테고리의 다른 글
[백준]- 1759 암호 만들기 (0) | 2021.03.16 |
---|---|
[백준] 14888번 연산자 끼워넣기 (0) | 2021.03.14 |
백준- 16506 CPU (0) | 2021.03.07 |
백준- 8911 거북이 (0) | 2021.03.07 |
백준- 13300 방 배정 (0) | 2021.02.22 |
댓글