Design a Snake game that is played on a grid of width width and height height. Play the game online if you are not familiar with the game.
The snake is initially positioned at the top-left cell (0, 0) with a length of 1 unit.
You are given a list of food's positions in the format of (row, col). The food is guaranteed to be placed on empty cells.
Each time the snake eats the food, its length and score increase by 1.
When the snake moves, the first cell the snake occupies is emptied, and the snake moves to the new cell. The snake dies if it moves out of bounds (not within width x height) or moves into a cell that is part of its body.
Implement the SnakeGame class:
SnakeGame(int width, int height, int[][] food) Initializes the object with the width and height of the game board and the food's positions.int move(String direction) Moves the snake. If the snake moves successfully, return the score after the move. Otherwise, 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 (snake moves right, no food).
snakeGame.move("D"); // return 0 (snake moves down, no food).
snakeGame.move("R"); // return 1 (snake moves right, eats the first food. The length of snake is now 2).
snakeGame.move("U"); // return 1 (snake moves up, no food)
snakeGame.move("L"); // return 2 (snake moves left, eats the second food. The length of snake is now 3).
snakeGame.move("U"); // return -1 (game over because snake collides with border).
Constraints:
1 <= width, height <= 1040 <= food.length <= 2000food[i].length == 20 <= food[i][0] < height0 <= food[i][1] < widthdirection.length == 1direction is 'U', 'D', 'L', or 'R'.104 calls will be made to move.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine guiding a snake across a grid as it moves step by step to eat food while trying not to bump into its own tail or the walls. The brute force approach involves keeping a complete mental picture of every single block the snake currently occupies on the board for every movement command you receive.
Here's how the algorithm would work step-by-step:
class SnakeGame:
def __init__(self, width: int, height: int, food: list):
self.board_width = width
self.board_height = height
self.food_items = food
self.food_index = 0
self.snake_body = [[0, 0]]
def move(self, direction: str) -> int:
current_head_row, current_head_col = self.snake_body[0]
if direction == "U":
next_head_row = current_head_row - 1
next_head_col = current_head_col
elif direction == "D":
next_head_row = current_head_row + 1
next_head_col = current_head_col
elif direction == "L":
next_head_row = current_head_row
next_head_col = current_head_col - 1
elif direction == "R":
next_head_row = current_head_row
next_head_col = current_head_col + 1
# We must check boundaries first because stepping outside causes an instant game over
if not (0 <= next_head_row < self.board_height and 0 <= next_head_col < self.board_width):
return -1
future_snake_body = self.snake_body[:-1]
# Self-collision check requires ignoring the tail since it will vacate the current cell
if [next_head_row, next_head_col] in future_snake_body:
return -1
has_food_available = self.food_index < len(self.food_items)
if has_food_available and self.food_items[self.food_index] == [next_head_row, next_head_col]:
self.food_index += 1
else:
self.snake_body.pop()
# Inserting the new head position simulates the forward crawl of the living snake
self.snake_body.insert(0, [next_head_row, next_head_col])
return len(self.snake_body) - 1To efficiently manage the snake's movement and growth, we need a way to track every part of its body in the exact order it spans across the board. The optimal strategy maintains a dedicated record of the snake's entire length, updating its position with each move while efficiently checking for collisions and food consumption.
Here's how the algorithm would work step-by-step:
from collections import deque
class SnakeGame:
def __init__(self, width: int, height: int, food: list[list[int]]):
self.board_width = width
self.board_height = height
self.food_sequence = deque(food)
self.snake_body = deque([[0, 0]])
self.snake_set = {(0, 0)}
self.current_score = 0
self.direction_map = {
'U': [-1, 0],
'L': [0, -1],
'R': [0, 1],
'D': [1, 0]
}
def move(self, direction: str) -> int:
row_offset, col_offset = self.direction_map[direction]
head_row, head_col = self.snake_body[0]
next_row = head_row + row_offset
next_col = head_col + col_offset
# Boundary and self-collision checks determine if the game ends prematurely.
if not (0 <= next_row < self.board_height and 0 <= next_col < self.board_width) or ((next_row, next_col) in self.snake_set and [next_row, next_col] != self.snake_body[-1]):
return -1
# Checking for available food at the next position allows the snake to grow.
if self.food_sequence and self.food_sequence[0] == [next_row, next_col]:
self.food_sequence.popleft()
self.current_score += 1
else:
tail_row, tail_col = self.snake_body.pop()
self.snake_set.remove((tail_row, tail_col))
self.snake_body.appendleft([next_row, next_col])
self.snake_set.add((next_row, next_col))
return self.current_score| Case | How to Handle |
|---|---|
| Snake hits the boundary walls during a movement command | Check the new head coordinates against grid width and height limits before updating the state to terminate the game correctly. |
| Snake runs into its own body segment | Maintain the snake body positions in a hash set to achieve efficient O(1) collision detection for any overlapping coordinates. |
| Snake successfully consumes food on the grid | Grow the snake by keeping the tail in place while advancing the head, and advance the food index to yield a score increment. |
| Snake moves into an empty cell without food | Advance the head to the new position and remove the tail segment from both the tracking queue and collision set to maintain correct length. |
| Snake moves into the exact position currently occupied by its own tail | Temporarily remove the tail from the body collision set before checking self-intersection since the tail will vacate that spot during a standard move. |
| All food items are exhausted before movement commands end | Treat subsequent moves as if no food is present on the board, allowing standard movement without score increases until the game terminates. |
| Minimum grid dimensions of width one and height one | Handle single-cell grids properly by immediately validating boundary and movement limits without causing index out of bounds exceptions. |
| A long sequence of movement commands with maximum constraints | Use a double-ended queue for the snake body and a hash set for positions to ensure every move is processed in efficient O(1) time complexity. |