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.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI