Design Snake Game
1 approach, code in every language
Problem description
Design the classic snake game played on a grid with the given width and height. The snake starts one cell long at the top-left corner, position row 0 and column 0, and food appears one piece at a time at the coordinates listed in the food array, in that order.
Implement the class SnakeGame with the constructor SnakeGame(width, height, food) and the method move(direction), where direction is one of the strings U, D, L, or R for up, down, left, and right. Each call advances the snake one cell in the requested direction. If the snake moves onto the current food cell, it grows by one and the next piece of food becomes active; otherwise its tail advances so its length stays the same.
The game ends, and move returns -1, if the snake runs into a wall or bites its own body. The subtle rule is that the snake may move into the cell its tail currently occupies, because the tail vacates that cell on the same step. Otherwise move returns the current score, which equals the snake length minus one.
Example 1
Input: operations = ["SnakeGame", "move", "move", "move", "move", "move", "move"] args = [[3, 2, [[1, 2], [0, 1]]], ["R"], ["D"], ["R"], ["U"], ["L"], ["U"]]
Output: [null, 0, 0, 1, 1, 2, -1]
On a 3 by 2 board the snake moves right then down with no score. Moving right onto [1, 2] eats the first food for score 1. Moving up then left onto [0, 1] eats the second food for score 2. The final up move leaves the board, ending the game with -1.
Example 2
Input: operations = ["SnakeGame", "move", "move"] args = [[2, 2, [[0, 1]]], ["R"], ["R"]]
Output: [null, 1, -1]
On a 2 by 2 board the snake starts at the top-left, moves right onto the food at [0, 1] to score 1, then moving right again runs off the board for game over.
Constraints
1 <= width, height <= 10^40 <= food.length <= 50 and food[i].length == 2, with 0 <= food[i][0] < height and 0 <= food[i][1] < widthdirection is one of U, D, L, or R, and at most 10^4 calls will be made to move.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free