Practice/Apple/Leetcode 353. Design Snake Game
CodingMust
Design and implement a classic Snake game that operates on an m × n grid. The snake starts at position (0, 0) with an initial length of 1 cell. Food items appear at predetermined locations on the grid in a specific sequence. When the snake's head reaches a food item, the snake consumes it, grows by one segment, and the player's score increases by 1.
Your implementation should support a move operation that advances the snake one cell in a given direction ("U" for up, "D" for down, "L" for left, "R" for right). The game ends when:
When the game ends, return -1. Otherwise, return the current score (number of food items eaten).
SnakeGame class with a constructor that accepts grid dimensions (width and height) and a list of food positionsmove(direction) method that moves the snake one step in the specified directionmoveExample 1:
` Grid: 3 rows × 2 columns Food: [[1,2], [0,1]]
Operations: move("R") → score = 0, snake at [0,1] move("D") → score = 0, snake at [1,1] move("R") → score = 1, snake at [1,2], ate food, length = 2 move("U") → score = 1, snake at [0,2] move("L") → score = 2, snake at [0,1], ate food, length = 3 move("U") → score = -1, game over (hit wall) `
Example 2:
` Grid: 3 rows × 3 columns Food: [[2,0]]
Operations: move("D") → score = 0, snake at [1,0] move("D") → score = 0, snake at [2,0], ate food, length = 2 move("R") → score = 1, snake at [2,1] move("U") → score = -1, game over (hit own body) `