Problem Description
Design a Snake game that is played on a board of size height x width. The snake starts at position (0, 0) with a length of 1 unit. You are given a list of food positions that appear one after the other. Each time the snake eats food, its length increases and so does the score. The game ends if the snake hits the wall or its own body (after moving).
Key Insights
- Use a deque (or linked list) to represent the snake’s body, where the head is at one end.
- Maintain a set for quick O(1) lookups to check if the snake collides with itself.
- When moving, compute the new head position using a direction map.
- Be careful when the snake eats food: do not remove the tail so the snake grows.
- For non-food moves, remove the tail before checking for collisions so that the tail cell becomes available.
Space and Time Complexity
Time Complexity: O(1) per move since each move involves a constant number of operations. Space Complexity: O(N + F) where N is the snake length (which is at most the number of moves) and F is the fixed number of food items.
Solution
The solution involves simulating the snake’s movement on the board. We store the snake’s positions in a deque, and a hash set is used to quickly check for collisions with its own body. Every call to move determines the new head position based on the input direction. We then check if the new position is out-of-bounds or if it collides with the snake itself (taking into account that if no food is eaten the tail is removed first). If the snake eats food, we increase the score and keep the tail intact to simulate growth. Otherwise, we remove the tail to keep the snake’s length constant. This strategy handles the simulation efficiently with constant time operations for each move.