Baekjoon 3190

Queue, Deque

Baekjoon 3190

Description

‘Dummy’ 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다.

게임은 NxN 정사각 보드위에서 진행되고, 몇몇 칸에는 사과가 놓여져 있다. 보드의 상하좌우 끝에 벽이 있다. 게임이 시작할때 뱀은 맨위 맨좌측에 위치하고 뱀의 길이는 1 이다. 뱀은 처음에 오른쪽을 향한다.

뱀은 매 초마다 이동을 하는데 다음과 같은 규칙을 따른다.

먼저 뱀은 몸길이를 늘려 머리를 다음칸에 위치시킨다.
만약 벽이나 자기자신의 몸과 부딪히면 게임이 끝난다.
만약 이동한 칸에 사과가 있다면, 그 칸에 있던 사과가 없어지고 꼬리는 움직이지 않는다.
만약 이동한 칸에 사과가 없다면, 몸길이를 줄여서 꼬리가 위치한 칸을 비워준다. 즉, 몸길이는 변하지 않는다.
사과의 위치와 뱀의 이동경로가 주어질 때 이 게임이 몇 초에 끝나는지 계산하라.

Input

첫째 줄에 보드의 크기 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가 증가하는 순으로 주어진다.

Output

첫째 줄에 게임이 몇 초에 끝나는지 출력한다.

Example I & O

Input
6
3
3 4
2 5
5 3
3
3 D
15 L
17 D

Output
9

Input
10
4
1 2
1 3
1 4
1 5
4
8 D
10 D
11 D
13 L

Output
21

Input
10
5
1 5
1 3
1 2
1 6
1 7
4
8 D
10 D
11 D
13 L

Output
13

My solution

import java.io.*;
import java.util.StringTokenizer;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Deque;


class Coordinate{
	private int x;
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	private int y;

	public Coordinate(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public boolean equals(Object other) {
		if (other == null)
			return false;
		if (getClass() != other.getClass())
			return false;
		else {
			Coordinate c_other = (Coordinate)other;

			return (x == c_other.x && y == c_other.y);
		}
	}

}

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int N = Integer.parseInt(br.readLine());
		int[][] snakeWorld = new int[N + 1][N + 1];
		int K = Integer.parseInt(br.readLine());
		StringTokenizer st = null;

		for (int i = 0; i < K; i++) {
			st = new StringTokenizer(br.readLine());
			int y = Integer.parseInt(st.nextToken());
			int x = Integer.parseInt(st.nextToken());

			snakeWorld[y][x] = 1;
		}

		Queue<Integer> times = new LinkedList<Integer>();
		Queue<String> turns = new LinkedList<String>();

		int L = Integer.parseInt(br.readLine());

		for (int i = 0; i < L; i++) {
			st = new StringTokenizer(br.readLine());
			times.add(Integer.parseInt(st.nextToken()));
			turns.add(st.nextToken());
		}

		int time = 0;
		String head_direction = "r";
		Deque<Coordinate> snake = new LinkedList<Coordinate>();
		snake.addFirst(new Coordinate(1, 1));

		while (true) {
			time++;
			int head_y = snake.peekFirst().getY();
			int head_x = snake.peekFirst().getX();
			int nextHead_y = head_y;
			int nextHead_x = head_x;

			if (head_direction.equals("r")) {
				nextHead_x++;
			}
			else if (head_direction.equals("l")) {
				nextHead_x--;
			}
			else if (head_direction.equals("u")) {
				nextHead_y--;
			}
			else {
				nextHead_y++;
			}

			if (nextHead_y > N || nextHead_x > N || nextHead_y < 1 || nextHead_x < 1)
				break;
			else if (snake.contains(new Coordinate(nextHead_x, nextHead_y)))
				break;

			if (snakeWorld[nextHead_y][nextHead_x] == 1) {
				snake.addFirst(new Coordinate(nextHead_x, nextHead_y));
				snakeWorld[nextHead_y][nextHead_x] = 0;
			}
			else {
				snake.addFirst(new Coordinate(nextHead_x, nextHead_y));
				snake.pollLast();
			}

			if (!times.isEmpty() && time == times.peek()) {
				times.poll();
				String direction_command = turns.poll();

				if (direction_command.equals("D")) {
					if (head_direction.equals("r"))
						head_direction = "d";
					else if (head_direction.equals("l"))
						head_direction = "u";
					else if (head_direction.equals("u"))
						head_direction = "r";
					else
						head_direction = "l";
				}
				else {
					if (head_direction.equals("r"))
						head_direction = "u";
					else if (head_direction.equals("l"))
						head_direction = "d";
					else if (head_direction.equals("u"))
						head_direction = "l";
					else
						head_direction = "r";
				}
			}


		}


		bw.write(time + "");


		bw.flush();
		bw.close();

	}

}
  • Sketch
    • Snake == Deque
    • Elements of deque are the coordinates of snake’s body parts
    • The coordinate of snake’s head is the first element of the deque
    • The coordinate of snake’s tail is the last element of the deque
    • The coordinates of snake’s body are the elements between the head and tail
    • The coordinate is (y, x)


  snake_head                                        snake_tail
      ---------------------------------------------------
  ←→  (1, 1)                                              ←→
      ---------------------------------------------------

First location of snake is (1, 1) (Snake's head location is (1, 1) and its size is 1 which is equal to the number of elements in deque)

Ex. Head Direction = Rightward (That is, its next moving direction is rightward: only x++)


  snake_head                     snake_tail
      -----------------------------------------
(1, 2)→                                 (1, 1) →                        
      -----------------------------------------

If there is no apple on the next location (only x++), the coordinate representing the next location of its head is added to the front side of deque (That is, check the head element of deque through peek() and calculate next coordinate. This coordinate gonna be added to the head)

Because its size is same, the last element (snake's tail) needs to be out

Ex. Head Direction = Rightward (That is, its next moving direction is rightward: only x++)


  snake_head                     snake_tail
      -----------------------------------------
(1, 3)→    (1, 2)                             
      -----------------------------------------

If there is an apple on the next location (only x++), the coordinate representing the next location of its head is added to the front side of deque (That is, check the head element of deque through peek() and calculate next coordinate. This coordinate gonna be added to the head)

Because its size gonna be +1, the last element (snake's tail) should not be out

Ex. Head Direction = Down (That is, its next moving direction is down: only y++)


  snake_head                     snake_tail
      -----------------------------------------
(2, 3)→ (1, 3)                         (1, 2)→                        
      -----------------------------------------

If there is no apple on the next location (only y++), the coordinate representing the next location of its head is added to the front side of deque (That is, check the head element of deque through peek() and calculate next coordinate. This coordinate gonna be added to the head)

Because its size is same, the last element (snake's tail) needs to be out

Ex. Head Direction = Down (That is, its next moving direction is down: only y++)


  snake_head                     snake_tail
      -----------------------------------------
(3, 3)→ (2, 3) (1, 3)                        
      -----------------------------------------

If there is an apple on the next location (only y++), the coordinate representing the next location of its head is added to the front side of deque (That is, check the head element of deque through peek() and calculate next coordinate. This coordinate gonna be added to the head)

Because its size gonna be +1, the last element (snake's tail) should not be out
If the next coordinate is outside the map or is in the deque, the game is over
  • Code Analysis


class Coordinate{
	private int x;
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	private int y;

	public Coordinate(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public boolean equals(Object other) {
		if (other == null)
			return false;
		if (getClass() != other.getClass())
			return false;
		else {
			Coordinate c_other = (Coordinate)other;

			return (x == c_other.x && y == c_other.y);
		}
	}

}

Coordinate class: the elements of deque (For easily dealing with x and y simultaneously)

I need to override “equals” method for using “contains” method which will be used to check whether its head reaches its body


int N = Integer.parseInt(br.readLine());
int[][] snakeWorld = new int[N + 1][N + 1];
int K = Integer.parseInt(br.readLine());
StringTokenizer st = null;

for (int i = 0; i < K; i++) {
  st = new StringTokenizer(br.readLine());
  int y = Integer.parseInt(st.nextToken());
  int x = Integer.parseInt(st.nextToken());

  snakeWorld[y][x] = 1;   
}

snakeWorld: for tracking the apples location

If there is an apple in snakeWorld(y, x), its value is 1 (The apples location will be 0 if the snake ate it)


Queue<Integer> times = new LinkedList<Integer>();
Queue<String> turns = new LinkedList<String>();

int L = Integer.parseInt(br.readLine());

for (int i = 0; i < L; i++) {
  st = new StringTokenizer(br.readLine());
  times.add(Integer.parseInt(st.nextToken()));
  turns.add(st.nextToken());
}

When the time reaches the element of times, its head’s direction changes

Based on the problem, the elements of times have already been ascending

Through 2 queues (one is for a time, the other is for the way of changing direction), change the direction of its head when it reaches the right time


int time = 0;
String head_direction = "r";
Deque<Coordinate> snake = new LinkedList<Coordinate>();
snake.addFirst(new Coordinate(1, 1));

while (true) {
  time++;
  int head_y = snake.peekFirst().getY();
  int head_x = snake.peekFirst().getX();
  int nextHead_y = head_y;
  int nextHead_x = head_x;

  if (head_direction.equals("r")) {
    nextHead_x++;
  }
  else if (head_direction.equals("l")) {
    nextHead_x--;
  }
  else if (head_direction.equals("u")) {
    nextHead_y--;
  }
  else {
    nextHead_y++;
  }

  if (nextHead_y > N || nextHead_x > N || nextHead_y < 1 || nextHead_x < 1)
    break;
  else if (snake.contains(new Coordinate(nextHead_x, nextHead_y)))
    break;


    ///
}

time: time passing from game start

At first, the direction of its head is rightward

First location of its head is (1, 1)

Based on “head_direction” and current coordinate of its head, calculate the next coordinate

If the next coordinate is outside the map or is in the deque, the game is over


if (snakeWorld[nextHead_y][nextHead_x] == 1) {
  snake.addFirst(new Coordinate(nextHead_x, nextHead_y));
  snakeWorld[nextHead_y][nextHead_x] = 0;
}
else {
  snake.addFirst(new Coordinate(nextHead_x, nextHead_y));
  snake.pollLast();
}

If there is an apple on the next location, the coordinate representing the next location of its head is added to the front side of deque

Because its size gonna be +1, the last element (snake’s tail) should not be out

snakeWorld(nextHead_y)(nextHead_x) has to be 0

If there is no apple on the next location, the coordinate representing the next location of its head is added to the front side of deque

Because its size is same, the last element (snake’s tail) needs to be out


if (!times.isEmpty() && time == times.peek()) {
  times.poll();
  String direction_command = turns.poll();

  if (direction_command.equals("D")) {
    if (head_direction.equals("r"))
      head_direction = "d";
    else if (head_direction.equals("l"))
      head_direction = "u";
    else if (head_direction.equals("u"))
      head_direction = "r";
    else
      head_direction = "l";
  }
  else {
    if (head_direction.equals("r"))
      head_direction = "u";
    else if (head_direction.equals("l"))
      head_direction = "d";
    else if (head_direction.equals("u"))
      head_direction = "l";
    else
      head_direction = "r";
  }
}

//outside While

bw.write(time + "");


bw.flush();
bw.close();

time reaches the head of “times” queue -> Change the direction of its head

“D” means the head turns right

Original Direction “Right” -> “Down”

Original Direction “Left” -> “Up”

Original Direction “Up” -> “Right”

Original Direction “Down” -> “Left”

“L” means the head turns left

Original Direction “Right” -> “Up”

Original Direction “Left” -> “Down”

Original Direction “Up” -> “Left”

Original Direction “Down” -> “Right”


© 2017. All rights reserved.

Powered by Hydejack v조현진