Design Snake Game Problem
Description
LeetCode Problem 353.
Design a Snake game that is played on a device with screen size height x width. Play the game online if you are not familiar with the game.
The snake is initially positioned at the top left corner (0, 0) with a length of 1 unit.
You are given an array food where food[i] = (r_i, c_i) is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game's score both increase by 1.
Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.
When a piece of food appears on the screen, it is guaranteed that it will not appear on a block occupied by the snake.
The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies after moving (i.e. a snake of length 4 cannot run into itself).
Implement the SnakeGame class:
SnakeGame(int width, int height, int[][] food)Initializes the object with a screen of sizeheight x widthand the positions of thefood.int move(String direction)Returns the score of the game after applying onedirectionmove by the snake. If the game is over, return-1.
Example 1:

Input
["SnakeGame", "move", "move", "move", "move", "move", "move"]
[[3, 2, [[1, 2], [0, 1]]], ["R"], ["D"], ["R"], ["U"], ["L"], ["U"]]
Output
[null, 0, 0, 1, 1, 2, -1]
Explanation
SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]);
snakeGame.move("R"); // return 0
snakeGame.move("D"); // return 0
snakeGame.move("R"); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1).
snakeGame.move("U"); // return 1
snakeGame.move("L"); // return 2, snake eats the second food. No more food appears.
snakeGame.move("U"); // return -1, game over because snake collides with border
Constraints:
1 <= width, height <= 10^41 <= food.length <= 50food[i].length == 20 <= r_i < height0 <= c_i < widthdirection.length == 1directionis'U','D','L', or'R'.- At most
10^4calls will be made tomove.
Solution
Approach: Queue of Body Cells + Hash Set
Simulate the game. The snake's body is a queue of cells: the head at one end, the tail at the other. Each move adds a new head and, unless the snake eats, removes the tail. A hash set holding the same cells answers "does the body cover this cell?" in O(1). We also keep the index of the next piece of food, and that index is also the score.
For each move:
- Compute the new head from the current head and the direction. If it is outside the
height x widthscreen, the game is over: return-1. - If the new head is on the current piece of food, the snake grows: the score goes up and the tail stays where it is.
- Otherwise the tail moves: remove the tail cell from the queue and the set.
- If the new head is now in the set, the snake bit itself: return
-1. - Add the new head to the queue and the set, and return the score.
The order of steps 3 and 4 matters. The tail moves away during the same move, so the head may enter the cell the tail is leaving. That is why a snake of length 4 can't run into itself, as the statement says, and why we remove the tail before checking for a collision. When the snake eats, the tail does not move, so that cell is still part of the body.
Complexity: O(1) time per move (average, for the hash set). O(L + F) space, where L is the snake's length and F the number of food pieces.
from collections import deque
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.width = width
self.height = height
self.food = food
self.eaten = 0 # also the score
self.body = deque([(0, 0)]) # head at the left end, tail at the right end
self.cells = {(0, 0)}
def move(self, direction: str) -> int:
dr, dc = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)}[direction]
r, c = self.body[0][0] + dr, self.body[0][1] + dc
if not (0 <= r < self.height and 0 <= c < self.width):
return -1
if self.eaten < len(self.food) and self.food[self.eaten] == [r, c]:
self.eaten += 1 # grow: the tail stays where it is
else:
# the tail moves away first, so the head may enter the cell it leaves
self.cells.remove(self.body.pop())
if (r, c) in self.cells:
return -1
self.body.appendleft((r, c))
self.cells.add((r, c))
return self.eaten