Problem of the day: Leetcode 909. Snakes and Ladders

 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 do not have a snake or ladder.

Note that you only take a snake or ladder at most once per move. 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 moves required to reach the square n2. If it is not possible to reach the square, return -1.

 

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
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
  • grid[i][j] is either -1 or in the range [1, n2].
  • The squares labeled 1 and n2 do not have any ladders or snakes.

Solution:
class Solution {
public:
    
    pair<int,int> posToIndex(int pos, int n){
        int i, j;
        i = (pos-1)/n;
        if(i%2 == 0){
            j = (pos-1)%n;
        }
        else{
            j = (n-1) - (pos-1)%n;
        }
        i = (n-1) - i;
        return {i,j};
    }
    
    int snakesAndLadders(vector<vector<int>>& board) {
        int n = board.size();
        queue<int> queue;
        unordered_set<int> visited;
        int moves = -1;
        
        queue.push(1);
        visited.insert(1);
        
        while(not queue.empty()){
            int size = queue.size();
            moves++;
            
            for(int i=0; i<size; i++){
                int curr = queue.front();
                queue.pop();
                
                if(curr == n*n){
                    return moves;
                }
                
                for(int k=curr+1; k<=min(curr+6, n*n); k++){
                    if(not visited.count(k)){
                        pair<int,int> pos = posToIndex(k, n);
                        int x = pos.first;
                        int y = pos.second;

                        visited.insert(k);

                        if(board[x][y] == -1){
                            queue.push(k);
                        }
                        else{
                            queue.push(board[x][y]);
                        }
                    }
                }
            }
        }
        
        return -1;
    }
};

This code defines a class "Solution" that contains a single public method "snakesAndLadders". The method takes in a 2D vector "board" as input, which represents a n x n game board of snakes and ladders.

The method first uses the helper function "posToIndex" to convert a given position on the board to its corresponding (row, column) index.

The method then uses a queue and an unordered_set to implement a Breadth-First Search (BFS) algorithm to find the minimum number of moves required to reach the last cell (n*n) on the board.

The algorithm starts by enqueuing the cell 1 and marking it as visited. In each iteration, the algorithm dequeues the front cell from the queue and checks if it is the last cell. If it is the last cell, the algorithm returns the number of moves required to reach that cell. Else, the algorithm enqueues all the possible cells that can be reached in one dice roll, ( curr+1 to min(curr+6, n*n) ). If a cell has a snake or ladder, the algorithm enqueues the destination cell of that snake or ladder instead of the current cell.

The time complexity of this algorithm is O(n^2) because the algorithm visits at most n^2 cells, and each cell is visited at most once. The space complexity of this algorithm is also O(n^2) because the algorithm stores at most n^2 cells in the queue and in the unordered_set.

In summary, the code above solves the problem of finding the minimum number of moves required to reach the last cell on the board by using a BFS algorithm, by using a queue, an unordered_set and a helper function posToIndex which convert a given position on the board to its corresponding (row, column) index.

The time complexity of this code is O(n^2). The algorithm visits at most n^2 cells and each cell is visited at most once. The while loop runs for at most n^2 iterations and each iteration takes O(n) time to process. So the total time complexity of the algorithm is O(n^2).

The space complexity of this code is O(n^2) as well. The algorithm uses a queue to store at most n^2 cells and an unordered_set to store at most n^2 visited cells. So the total space complexity of the algorithm is O(n^2).



Comments