All problems
0534MediumArrayBreadth-First SearchMatrix

Fewest Rolls on the Chute Board

Tracked in this browser only
Write code

Trains the technique from

LeetCode 909Snakes and Ladders

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A promotional game is played on a square board of n * n tiles, handed to you as the grid board. The tiles are numbered 1 to n * n in a back-and-forth path: numbering starts at the bottom-left cell of the grid and runs left to right along the bottom row, then right to left along the row above it, then left to right again, alternating direction on every row up to the top one.

A cell holds either -1, meaning its tile is ordinary, or the number of another tile, meaning a chute leaves that tile: a counter that lands on it is carried straight to the tile written in the cell. A counter carried by a chute stays put once it arrives, even if the tile it arrives on also has a chute leaving it. Tile 1 and tile n * n are never the start of a chute.

The counter begins on tile 1. One turn means picking a number of tiles to advance, anything from 1 to 6, moving the counter that far along the numbering, and then taking the chute from the tile it landed on if there is one. Advancing past tile n * n is not allowed, so near the end the choice narrows.

Return the fewest turns needed to bring the counter to tile n * n, or -1 if no sequence of turns gets it there.

Examples

Example 1

Input
board = [[-1, -1], [-1, -1]]
Output
1

The tiles run 1, 2 along the bottom row and then 4, 3 along the top row. Advancing three tiles from tile 1 lands on tile 4, which is the last tile, so one turn is enough.

Example 2

Input
board = [[-1, -1, -1], [-1, -1, -1], [-1, -1, 9]]
Output
1

The cell at row 2, column 2 is tile 3, and its chute leads to tile 9. Advancing two tiles from tile 1 lands on tile 3, which carries the counter to tile 9 in the same turn.

Example 3

Input
board = [[2, 2, -1], [2, 2, 2], [-1, -1, 2]]
Output
-1

Every tile from 3 to 8 has a chute back to tile 2, and from tile 2 only tiles 3 to 8 are within reach, so the counter can never arrive at tile 9.

Constraints

  • n == board.length == board[i].length
  • 2 <= n <= 20
  • board[i][j] is -1 or a tile number in the range [1, n * n].
  • Neither tile 1 nor tile n * n is the start of a chute.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_rolls(board: list[list[int]]) -> int:
Java
public int fewestRolls(int[][] board)
September 7
Apply