Leetcode 909: Snakes and Ladders

grid47
grid47
Exploring patterns and algorithms
Aug 8, 2024 7 min read

You are given an n x n integer matrix board where the cells are numbered from 1 to n² in a zigzag pattern starting from the bottom-left corner. Each cell may contain either -1 (indicating no special feature) or a number indicating a snake or ladder destination. You start at square 1 and can roll a 6-sided die to move between 1 and 6 steps. If you land on a square with a snake or ladder, you must move to its destination. Determine the minimum number of dice rolls needed to reach the final square . Return -1 if it is not possible.
Problem
Approach
Steps
Complexity
Input: An `n x n` matrix `board` where each cell represents a square in the game, containing either `-1` or a number indicating a snake or ladder destination.
Example: Input: board = [[-1,-1,-1],[-1,-1,-1],[-1,-1,2]]
Constraints:
• n == board.length == board[i].length
• 2 <= n <= 20
• board[i][j] is either -1 or in the range [1, n²]
• Squares 1 and n² are not the start of any snake or ladder.
Output: The minimum number of dice rolls required to reach the final square `n²`. If unreachable, return -1.
Example: Output: 3
Constraints:
Goal: Use Breadth-First Search (BFS) to calculate the minimum steps to reach square `n²`.
Steps:
• Convert the 2D matrix to a 1D representation for easier traversal.
• Use BFS starting from square 1, keeping track of visited squares to avoid revisits.
• For each square, simulate a dice roll (1 to 6 steps) and determine the next position.
• If a square has a snake or ladder, move to its destination; otherwise, move normally.
• If the final square `n²` is reached, return the current roll count. If the queue is empty and `n²` is not reached, return -1.
Goal: Limitations and conditions for the game board and movement.
Steps:
• The board is always square (n x n).
• Values in the board are either `-1` or valid destinations within the range of the board.
• There are no snakes or ladders at squares 1 and `n²`.
Assumptions:
• The board dimensions are valid (n x n).
• Dice rolls always provide up to 6 possible moves unless constrained by board size.
Input: Input: board = [[-1,-1,-1],[6,-1,-1],[-1,-1,2]]
Explanation: Start at square 1. Move to square 2 and follow the ladder to square 6. Then, roll to square 7 and follow the snake to square 2. Finally, roll to square 9 to win in 3 moves.

Input: Input: board = [[-1,-1],[-1,-1]]
Explanation: There are no snakes or ladders. The quickest path is to roll the dice 2 times to reach square 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus