Snakes and Ladders: The Quickest Way Up

  • + 0 comments

    "Snakes and Ladders: The Quickest Way Up" problem, we can use the Breadth-First Search (BFS) algorithm. Below is the PHP solution for this problem:

    <?php
    
    function quickestWayUp($ladders, $snakes) {
        $board = array_fill(1, 100, 0);
    
        // Set up ladders
        foreach ($ladders as $ladder) {
            $board[$ladder[0]] = $ladder[1] - $ladder[0];
        }
    
        // Set up snakes
        foreach ($snakes as $snake) {
            $board[$snake[0]] = $snake[1] - $snake[0];
        }
    
        // BFS to find the shortest path
        $queue = [[1, 0]];
        $visited = array_fill(1, 100, false);
        $visited[1] = true;
    
        while (!empty($queue)) {
            list($current, $moves) = array_shift($queue);
    
            for ($dice = 1; $dice <= 6; $dice++) {
                $next = $current + $dice;
                if ($next <= 100) {
                    $next += $board[$next];
    
                    if ($next == 100) {
                        return $moves + 1;
                    }
    
                    if (!$visited[$next]) {
                        $visited[$next] = true;
                        array_push($queue, [$next, $moves + 1]);
                    }
                }
            }
        }
    
        return -1;
    }
    
    ?>
    

    Explanation:

    1. Initialization:

      • The board array stores the effect of ladders and snakes on each cell.
      • queue is used for BFS, initialized with the starting position (1, 0) representing the start of the board and 0 moves.
      • visited array keeps track of visited cells to avoid revisiting them.
    2. Setup Ladders and Snakes:

      • For ladders, the board at the start cell of the ladder has the value of the end cell minus the start cell.
      • Similarly, for snakes, the board at the start cell of the snake has the value of the end cell minus the start cell.
    3. BFS to Find Shortest Path:

      • Dequeue the current position and number of moves.
      • For each dice roll (1 to 6), calculate the next position.
      • Apply any ladder or snake effect.
      • Check if the next position is 100 (end of the board).
      • If not visited, mark it as visited and enqueue it with incremented move count.
    4. Handling Input:

      • The readInput function reads the input from standard input and processes it.
      • For each test case, read the number of ladders and snakes, and their respective positions.
      • Call the quickestWayUp function for each test case and print the result.