909. Snakes and Ladders

You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.

You start on square 1 of the board. In each move, starting from square curr, do the following:

  • Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].
    • This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
  • If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.
  • The game ends when you reach the square n2.

A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder.

Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.

  • For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.

Return the least number of dice rolls required to reach the square n2. If it is not possible to reach the square, return -1.

 

Example 1:

snakes-board

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
Explanation: 
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.

Example 2:

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

 

Constraints:

  • n == board.length == board[i].length
  • 2 <= n <= 20
  • board[i][j] is either -1 or in the range [1, n2].
  • The squares labeled 1 and n2 are not the starting points of any snake or ladder.

Approach 01:

class Solution {
public:
    int snakesAndLadders(vector<vector<int>>& board) {
        int n = board.size();
        vector<int> flattenedBoard(n * n);
        int row = n - 1, col = 0, index = 0, direction = 1;

        while (index < n * n) {
            flattenedBoard[index++] = board[row][col];
            if (direction == 1 && col == n - 1) {
                direction = -1;
                row--;
            } else if (direction == -1 && col == 0) {
                direction = 1;
                row--;
            } else {
                col += direction;
            }
        }

        vector<bool> visited(n * n, false);
        queue<int> bfsQueue;
        int startSquare = flattenedBoard[0] > -1 ? flattenedBoard[0] - 1 : 0;

        bfsQueue.push(startSquare);
        visited[startSquare] = true;

        int moves = 0;

        while (!bfsQueue.empty()) {
            int levelSize = bfsQueue.size();
            while (levelSize-- > 0) {
                int current = bfsQueue.front();
                bfsQueue.pop();

                if (current == n * n - 1){
                    return moves;
                }
                    
                for (int next = current + 1;
                    next <= min(current + 6, n * n - 1); ++next) {
                    int destination = flattenedBoard[next] > -1 ? flattenedBoard[next] - 1 : next;
                    if (!visited[destination]) {
                        visited[destination] = true;
                        bfsQueue.push(destination);
                    }
                }
            }
            ++moves;
        }

        return -1;
    }
};
from collections import deque

class Solution:
    def snakesAndLadders(self, board: list[list[int]]) -> int:
        n = len(board)
        flattenedBoard = [0] * (n * n)
        row, col, index, direction = n - 1, 0, 0, 1

        while index < n * n:
            flattenedBoard[index] = board[row][col]
            index += 1
            if direction == 1 and col == n - 1:
                direction = -1
                row -= 1
            elif direction == -1 and col == 0:
                direction = 1
                row -= 1
            else:
                col += direction

        visited = [False] * (n * n)
        bfsQueue = deque()
        startSquare = flattenedBoard[0] - 1 if flattenedBoard[0] > -1 else 0

        bfsQueue.append(startSquare)
        visited[startSquare] = True

        moves = 0

        while bfsQueue:
            for _ in range(len(bfsQueue)):
                current = bfsQueue.popleft()

                if current == n * n - 1:
                    return moves

                for nextSquare in range(current + 1, min(current + 6, n * n - 1) + 1):
                    destination = flattenedBoard[nextSquare] - 1 if flattenedBoard[nextSquare] > -1 else nextSquare
                    if not visited[destination]:
                        visited[destination] = True
                        bfsQueue.append(destination)

            moves += 1

        return -1

Time Complexity:

  • Flattening the board:

    We iterate through the entire 2D board of size \(n \times n\) once → \(O(n^2)\).

  • BFS Traversal:

    Each square can be visited once, and from each square we consider up to 6 moves → \(O(n^2)\).

  • Total Time Complexity:

    \(O(n^2)\).

Space Complexity:

  • Flattened board and visited array:

    Both are of size \(n^2\) → \(O(n^2)\).

  • BFS Queue:

    In the worst case, it may hold up to \(O(n^2)\) elements → \(O(n^2)\).

  • Total Space Complexity:

    \(O(n^2)\).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top