Snake Game
Time limit1sMemory limit1024 MB
Find the maximum length a snake can reach on an arrow grid, where apples change its path and the game ends when the head hits its body or the wall.
- Level
Hard8 of 10
- Topics
- Graph, Simulation, Implementation
- Solved
- No attempts yet
Problem
Sookkek took part in Myeongrang Hajae, the annual freshman game development event run by the KAIST game development club Hajae, and built an automated snake game. The goal is to make the snake as long as possible to raise the score. The map is a grid of rows and columns of rectangular tiles.
- Every tile has one of an up, right, down, or left arrow.
- Some tiles have an apple on them.
One snake is on the map. It consists of a head, a body, and a tail. Among the tiles the snake occupies, the one it occupied last is the head, and the one it occupied first is the tail. The rest are body tiles. At the start, the snake occupies two adjacent tiles, one head and one tail. The starting score is the number of tiles the snake occupies. The snake repeats the following steps.
- Choose the tile where the head grows. The new head is the cell one step from the current head in the direction of the arrow on the head's tile.
- However, if the arrow on the tile points opposite to the snake's moving direction, ignore the arrow and take the cell one step in the moving direction instead.
- At the start, the snake's moving direction is from the tail toward the head.
- If there is no apple at the new head position, or the position is outside the map, the snake leaves the tail tile and no longer occupies it. The first tile the snake occupied among the remaining tiles becomes the new tail.
- If there is an apple at the new head position, the snake eats it. An eaten apple disappears.
- The snake occupies the new head position. If this position is outside the map or already occupied by the snake, the game ends immediately.
- The score becomes the total number of tiles the snake occupies.
Sookkek wants to know the maximum score this game can reach. Find it for him while he is busy drawing art.
Input
The first line contains , , , , , and , separated by spaces. The map has rows and columns. The snake's starting head is at , and its starting tail is at . The top-left tile is , and the tile in row and column is . (; ; ; )
The next lines each contain integers from to , separated by spaces. The -th number on the -th line is the arrow on tile . Up, right, down, and left arrows are .
The next line contains the number of apples . ()
The next lines each contain two integers and , separated by a space. The -th apple is at . No tile has two or more apples, and no apple is on the tile where the snake starts. (; )
Output
Print the maximum score this game can reach.
Hint
The game may never end depending on the map.