Skip to content
RED SAGSkills

Simulate a Snake Game

Simulate the classic Snake game on a grid width x height; cell [x, y] is column x, row y, with [0, 0] at the top-left. The snake starts with length 1 at [0, 0].

Food appears one piece at a time in the order given by food: only food[0] is on the board at first, and the next piece appears as soon as the current one is eaten. Each character of moves (U, D, L, R) moves the head one cell.

For each move: if the new head is outside the grid, the snake dies. If the new head is on the current food, the snake grows (its tail stays) and the score goes up by 1, unless the head hits its own body, in which case it dies. Otherwise the tail moves first, so the head may enter the cell the tail just left, and the snake dies if the head hits the rest of its body. After death no more moves are processed, and the fatal move earns no points.

Return { score, alive, steps }, where steps counts the moves completed without dying.

Example 1

Input: width = 3, height = 3, food = [[1,0],[2,0]], moves = "RRD"
Output: {"score":2,"alive":true,"steps":3}
Explanation: Eats both pieces, then moves down safely.

Example 2

Input: width = 2, height = 2, food = [], moves = "RR"
Output: {"score":0,"alive":false,"steps":1}
Explanation: The second move leaves the 2 x 2 board.

Constraints

  • 1 <= width, height <= 10^4
  • 0 <= food.length <= 10^4
  • 0 <= moves.length <= 10^5
  • Food never appears on the snake body
Hint 1

Keep the body in a queue (head at one end) plus a Set of occupied cells.

Hint 2

Remove the tail from the set before checking a normal move.

Good practice for: Game Developer, Frontend Developer, Mobile App Developer, Embedded Systems Engineer, Automation Test Engineer

Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.