Snakes and Ladders

You are given an `n x n` board whose squares are numbered 1 to n² in a zigzag (boustrophedon) order: starting at the bottom-left, row by row upward, alternating direction each row. You start on square 1. Each move you roll a six-sided die and move to any square from `curr + 1` to `min(curr + 6, n²)`. If that square holds a snake or ladder (`board[r][c] != -1`), you must move to its destination `board[r][c]`, but you do not follow a second snake or ladder in the same move. Return the fewest moves needed to reach square n², or -1 if it cannot be reached.

30:00

Snakes and Ladders
medium
Free written solution
Topics
Companies

You are given an n x n board whose squares are numbered 1 to n² in a zigzag (boustrophedon) order: starting at the bottom-left, row by row upward, alternating direction each row. You start on square 1. Each move you roll a six-sided die and move to any square from curr + 1 to min(curr + 6, n²). If that square holds a snake or ladder (board[r][c] != -1), you must move to its destination board[r][c], but you do not follow a second snake or ladder in the same move. Return the fewest moves needed to reach square n², or -1 if it cannot be reached.

Example 1:
Input: {"board":[[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]}
Output: 4
Constraints:
  • n==board.length==board[i].lengthn == \text{board.length} == \text{board}[i].\text{length}

  • 2≤n≤202 \leq n \leq 20

  • board[i][j]\text{board}[i][j] is −1-1 or in the range [1,n2][1, n^2]

  • Squares 1 and n2n^2 are not the start of any snake or ladder

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"board":[[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]}

The board has 36 squares numbered in a zigzag from the bottom-left. Start BFS from square 1, which costs 0 moves.

current

-

moves

0

reached

1/36

answer

?

1023456789101112131415161718192021222324252627282930313233343536
--- ladder~ snake□ die landingnumber in a square = fewest moves

queue (1)

1·0
Variables
VariableValue
n6
target36
queue[1]
DepthFunction Call
Stack empty
0/54