Gamified challenge · Deques
The garden is a grid with height rows and width columns. The worm starts as one segment at row 0, column 0. moves is a string of U, D, L, R; each letter moves the head one cell. Apples appear one at a time: food[0] (a [row, col] pair) is on the grid first, and food[k + 1] appears only after food[k] is eaten. An apple never appears on the worm.
On each move: if the head would leave the grid, the game is over. If the head lands on the current apple, the worm eats it (score + 1) and grows: the tail stays put. Otherwise the tail moves forward one cell first, so the head may step into the cell the tail just left. If the head lands on any other part of the body, the worm bites itself and the game is over.
Write play(width, height, food, moves) that returns the score when the game ends or the moves run out. With width = 3, height = 2, food = [[1, 2], [0, 1]] and moves = "RDRULU" the worm eats both apples and then leaves the grid on the last U, so the answer is 2.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google