1704. Snake Board
Build a small snake game on a board with height rows and width columns. The snake starts with length 1 at row 0, column 0. Design a class SnakeBoard whose constructor receives width, height and the list food, where food[i] = [row, col]. Food items appear one at a time in the given order: food[i + 1] appears only after food[i] has been eaten.
move(direction) with "U", "D", "L" or "R" advances the head one cell and returns the number of food items eaten so far, or -1 if the game is over. The game ends when the head leaves the board or runs into the snake's body; after that every move returns -1. Eating the active food makes the snake one cell longer. On a move that does not eat, the tail leaves its cell first, so the head may enter the cell the tail just left. Food never appears on the snake. A deque for the body plus a hash set of cells gives O(1) per move.
Example 1
- Input:
- operations = ["SnakeBoard","move","move","move","move"]arguments = [[3,2,[[0,1],[1,2]]],["R"],["D"],["R"],["R"]]
- Output:
- [null,1,1,2,-1]
- Explanation:
Moving right eats (0, 1) giving 1, moving down changes nothing, moving right eats (1, 2) giving 2, and the next right leaves the 3-column board so the result is -1.
Example 2
- Input:
- operations = ["SnakeBoard","move","move","move"]arguments = [[2,2,[]],["D"],["R"],["D"]]
- Output:
- [null,0,0,-1]
- Explanation:
Without food the snake stays at length 1: down to (1, 0) and right to (1, 1) both return 0, and the next down leaves the board.
Example 3
- Input:
- operations = ["SnakeBoard","move","move","move","move","move","move"]arguments = [[4,4,[[0,1],[0,2],[1,2]]],["R"],["R"],["D"],["L"],["U"],["R"]]
- Output:
- [null,1,2,3,3,3,3]
- Explanation:
After eating three items the snake has length 4 and chases its own tail: each of the last three moves enters the cell the tail has just vacated, so they are legal and the count stays 3.
Constraints
1 ≤ width, height ≤ 104
0 ≤ food.length ≤ 50
food never appears on the snake
At most 1000 moves
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) per move
- Space
- O(L + f)