Tuesday, May 28, 2024

[LeetCode] Snakes and Ladders

Problem: You are given an n x n integer matrix board where the cells are labeled from 1 to n^2 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, n^2)].
    • 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 n^2.

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:

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.


Approach: This is again a BFS problem. You can assume the snake and ladder board as a graph in which one cell is connected to another cell using snake or ladder. Now we need to find the path with minimum nodes from 1 to n*n, which is clearly a BFS problem.

Now the only thing we need is given the number next , we need to calculate it's cell (row, col).


Implementation in C#:

    public int SnakesAndLadders(int[][] board)
    {
        int n = board?.Length ?? 0;
        if (n == 0)
        {
            return 0;
        }
        int numOfSteps = 0;
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(1);
        HashSet<int> visited = new HashSet<int>();
        while (queue.Count > 0)
        {
            ++numOfSteps;
            int size = queue.Count;
            for (int i = 0; i < size; ++i)
            {
                int curr = queue.Dequeue();
                for (int j = 1; j <= 6; ++j)
                {
                    int next = curr + j;
                    // Reached target
                    if (next == n * n)
                    {
                        return numOfSteps;
                    }
                    int row = 0;
                    int col = 0;
                    // Get cell of the given number next
                    this.GetNextRowColumn(next, n, ref row, ref col);
                    // if curr cell is snake or stair
                    if (board[row][col] != -1)
                    {
                        next = board[row][col];
                    }
                    // Reached target
                    if (next == n * n)
                    {
                        return numOfSteps;
                    }
                    if (!visited.Contains(next))
                    {
                        visited.Add(next);
                        queue.Enqueue(next);
                    }
                }
            }
        }
        return -1;
    }

    private void GetNextRowColumn(int next, int n, ref int row, ref int col)
    {
        row = next / n;
        col = next % n;
        if (col == 0)
        {
            col = n;
            --row;
        }
        col = row % 2 == 0 ? col - 1 : n - col;
        row = n - 1 - row;
    }


Complexity: O(n^2)

No comments:

Post a Comment