Tutorialspoint
Problem
Solution
Submissions

Snake Game

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to design a Snake game that is played on a device with screen size = width x height. The snake starts at position [0,0] with length 1 unit and moves towards the right. The game should support four directions: 'U' (up), 'D' (down), 'L' (left), 'R' (right). Food will appear at a random position. The snake can grow in length when it eats the food. The game is over when the snake hits the screen boundaries or itself.

Example 1
  • Input: width = 3, height = 2, food = [[1,2]], Moves: ["R","D","R"]
  • Output: [1]
  • Explanation:
    • Initial screen:
      S..
      ...
    • After "R":
      .S.
      ...
    • After "D":
      ...
      .S.
    • After "R" (eating food):
      ...
      ..S
    • Score = 1
Example 2
  • Input: width = 3, height = 3, food = [[0,1], [1,2]], Moves: ["R","R","U","U","L"]
  • Output: [2]
  • Explanation:
    • The snake eats both food items and grows to length 3 but then hits itself.
Constraints
  • 1 ≤ width, height ≤ 10
  • 1 ≤ food.length ≤ 50
  • food[i] = [row, col] where 0 ≤ row < height and 0 ≤ col < width
  • 1 ≤ moves.length ≤ 10000
  • moves only contains the characters 'U', 'D', 'L', and 'R'
  • Time Complexity: O(m) where m is the number of moves
  • Space Complexity: O(width * height) for storing the game state
ArraysControl StructureseBaySnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a deque (double-ended queue) to represent the snake's body.
  • Use a set to track the positions occupied by the snake.
  • Implement a move function that updates the snake's position based on the direction.
  • Check for collisions with boundaries and the snake's own body.
  • Handle the case when the snake eats food by growing its length.

Steps to solve by this approach:

 Step 1: Define the game parameters including width, height, food positions, and snake initial position.
 Step 2: Use a LinkedList to represent the snake's body, where the first node is the head and the last node is the tail.
 Step 3: Use a HashSet to quickly check if a position is occupied by the snake.
 Step 4: For each move, calculate the new head position based on the direction.
 Step 5: Check if the new position would cause a collision with the boundaries or the snake itself.
 Step 6: Check if the new position contains food. If yes, increase the score and don't remove the tail.
 Step 7: If no food is eaten, remove the tail from both the LinkedList and the HashSet.

Submitted Code :