Taro Logo

Design Snake Game

#14 Most AskedMedium
0 views
Topics:
Arrays

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 <= 104
  • 0 <= food.length <= 2000
  • food[i].length == 2
  • 0 <= food[i][0] < height
  • 0 <= food[i][1] < width
  • direction.length == 1
  • direction is 'U', 'D', 'L', or 'R'.
  • At most 104 calls will be made to move.

Solution


Clarifying Questions

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:

  1. What are the dimensions (width and height) of the grid, and what is the maximum number of moves or food items we can expect?
  2. How are the movement commands represented in the input (e.g., strings like 'U', 'D', 'L', 'R' or directional vectors), and what should be returned if the input command sequence finishes completely without the snake dying?
  3. When the snake eats food, does its body grow before or after it moves, and does it grow immediately upon entering the food cell?
  4. If the snake moves into the exact position where its tail currently is, does it constitute a self-collision (game over) given that the tail will vacate that spot simultaneously?
  5. What is the format of the food input? Is it a list of coordinate pairs, and can food spawn outside the grid boundaries or on top of the snake's initial position?

Brute Force Solution

Approach

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:

  1. Whenever a movement command is given, look at the very front of the snake and determine the new spot where its head is supposed to move.
  2. Check if this new spot takes the snake outside the board boundaries, which would mean the game is over.
  3. Check if this new spot overlaps with any part of the snake's body currently resting on the board, which would also mean the game is over.
  4. Look ahead to see if there is food waiting at this new spot.
  5. If there is food waiting, let the snake grow by keeping all its current body parts in place and adding the new spot to the front.
  6. If there is no food, make the snake crawl forward by adding the new spot to the front while completely forgetting about the very last spot at the tail end so the snake stays the same length.
  7. Count how many pieces of food the snake has successfully eaten so far and keep this number ready to share as the current score.

Code Implementation

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) - 1

Big(O) Analysis

Time Complexity
O(k) – For each movement command executed by the snake, we determine the new head position and check if it collides with the body or walls in constant time if using a set. If no food is eaten, we remove the tail in constant time, meaning each move operation takes time proportional to k, the current length of the snake. Over the course of the game, since the snake's length k is bounded by the total number of cells on the board or the number of movement commands, checking body collisions dominates. This leads to operations scaled by the length of the snake per move, simplifying to O(k) time complexity per command.
Space Complexity
O(min(W * H, K)) – To track the positions occupied by the snake and perform fast collision checks, we maintain a double-ended queue and a hash set storing the coordinates of every body segment. As the snake eats food and grows up to a maximum length of N, where N is the total number of cells on the board given by width W times height H or capped by the number of food items K, the extra memory scales proportionally. Therefore, the auxiliary space complexity is driven by these data structures and grows linearly with the length of the snake.

Optimal Solution

Approach

To 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:

  1. Keep track of the complete path that the snake currently occupies, noting where its head is and where its tail is.
  2. When a movement command is given, look at where the head is about to land based on the direction provided.
  3. Check if the newly projected head position goes outside the allowed boundaries of the board, which would mean the game is lost.
  4. Check if the newly projected head position collides with any part of the snake's current body, except for the very end of the tail which will move away, resulting in a game loss if a collision happens.
  5. Check if there is food waiting at the newly projected head position.
  6. If there is food, allow the snake to grow by keeping its tail in place while the head moves to the new spot, and advance to the next piece of food.
  7. If there is no food, move the head to the new spot and remove the rearmost part of the tail so the snake maintains its exact length while shifting forward.
  8. Return the current score, which is based on how many pieces of food have been successfully eaten along the way.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(1) – For each movement command executed by the snake, calculating the new head position and checking board boundaries or food consumption takes constant time. Although checking for body collisions involves verifying if the new head coordinate exists within the snake's body tracking structure, the maximum length of the snake and the size of this lookup collection are bounded by the constant number of grid cells. Therefore, the operations required per move do not scale with an external input size, resulting in a constant time complexity of O(1) per move.
Space Complexity
O(L) – To track the complete path of the snake as described in step one, we use a doubly-ended queue or similar list alongside a hash set, where L represents the current length of the snake. These data structures store every coordinate occupied by the snake's body segments to handle movement, growth, and collision checks in steps four and seven. As the snake eats food and grows up to a maximum length bounded by the total number of food items or board cells, the memory consumed by these tracking collections scales linearly with that length. Therefore, the auxiliary space complexity evaluates to O(L), where L is the maximum length of the snake during the game.

Edge Cases

Snake hits the boundary walls during a movement command
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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.
0/17 completed