Leetcode Problem 353. Design Snake Game

353. Design Snake Game

Leetcode Solutions

Queue and Hash Set Approach for Snake Game

  1. Initialize a Queue to represent the snake's body, starting with the head at position (0,0).
  2. Initialize a Hash Set to store the positions of the snake's body for quick collision checks.
  3. Store the food positions in a list or array.
  4. For each move: a. Calculate the new head position based on the direction. b. Check if the new head position is out of bounds or collides with the snake's body using the Hash Set. If so, return -1 (game over). c. Check if the new head position is at the next food location. If so, increase the score and update the food list. d. If no food is consumed, remove the tail from the Queue and Hash Set. e. Add the new head to the Queue and Hash Set.
  5. Return the current score after each move.
UML Thumbnail

Array-based Approach for Snake Game

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...