Colorful Snake
InterviewTime limit32sMemory limit1024 MB
Simulate a snake that moves on an m by m board, eats colored snacks, and report the color of the segment in a queried cell after each query.
- Level
Medium4 of 10
- Topics
- Simulation, Hash map, Queue
- Solved
- No attempts yet
Problem
Years ago, Bajtazar played the Snake game on his old mobile phone. Today he works as a programmer, and out of nostalgia he wants to write his own version. It is 2022, so he wants to add some color and move the game to a much larger computer screen. Your task is to help him write one module of the game.
The game is played on a square board with rows and columns, so the board has cells. Rows are numbered 1 to from top to bottom, and columns are numbered 1 to from left to right. All colors are numbered from 0 to .
At the start, a snake made only of its head is in the cell at row 1, column 1. The head has color 0. There are snacks on the board. Each snack occupies one cell and has a color. Snack colors may repeat.
In each time unit, the player moves the head one cell up, down, left, or right. The rest of the snake follows the head. The cell the head occupied before the move is now occupied by the second segment, the cell of the second segment is taken by the third segment, and so on. The head never moves into the cell of the first segment behind it, so the snake never turns back. The head may not leave the board or enter a cell that holds another segment of the snake. If it does, the player loses.
When the head moves onto a cell with a snack, the snake eats it. The snack disappears from the board and the snake grows by one segment. The head takes the color of the eaten snack and ends the move on that cell. The other segments do not move during that move.
You may assume that the snake never leaves the board and never enters a cell occupied by its own segments.
Input
The first line contains three integers , , and . They are the side length of the board, the number of snacks on the board, and the number of commands to process.
Each of the next lines contains three integers , , and . This means there is a snack of color in row , column . Here and . All pairs are distinct and none of them is the starting cell (1, 1).
Each of the next lines is a command. A command is one of the letters G, D, L, or P, or the letter Z followed by two integers and . G means the head moved up, D means it moved down, L means it moved left, and P means it moved right. The command Z w' k' asks for the color of the snake segment in row , column at the current moment. You may assume there is at least one such query.
Output
For each query, print one line with one integer. Print the color of the snake segment occupying the queried cell at that moment, as an integer in the range . If no segment of the snake occupies that cell at that moment, print -1.