Rotating the Box

We can solve this problem by performing two steps:

  1. Handle the Gravity: Simulate the falling of stones within each row. Iterate through each row from left to right and keep track of the number of stones and their rightmost position relative to obstacles. When an obstacle is found, fill the rightmost available positions with stones and clear the original positions.

  2. Rotate the Box: After simulating gravity, create a new 2D array with dimensions switched (i.e., n x m) and fill it with the rotated values of the original array.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        # Simulate the falling of stones within each row
        for row in box:
            rightmost_empty = len(row) - 1
            stones = 0
            for i in reversed(range(len(row))):
                if row[i] == '#':
                    stones += 1
                    row[i] = '.'
                elif row[i] == '*':
                    for _ in range(stones):
                        row[rightmost_empty] = '#'
                        rightmost_empty -= 1
                    stones = 0
                    rightmost_empty = i - 1
            for _ in range(stones):
                row[rightmost_empty] = '#'
                rightmost_empty -= 1

        # Rotate the box 90 degrees clockwise
        m, n = len(box), len(box[0])
        rotated_box = [['.' for _ in range(m)] for _ in range(n)]
        for i in range(m):
            for j in range(n):
                rotated_box[j][m - i - 1] = box[i][j]

        return rotated_box

Explanation:

  • In the first loop, we iterate through each row and handle the gravity within the row.
  • In the second loop, we create a new 2D array and fill it with the values from the original array, rotated 90 degrees clockwise.

This solution handles the gravity within each row independently and then constructs the final rotated array, satisfying the given constraints and requirements.