
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
- Initial screen:
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
Editorial
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. | ||||
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.