Rotating the Box Problem
Description
LeetCode Problem 1861.
You are given an m x n matrix of characters boxGrid representing a side-view of a box. Each cell of the box is one of the following:
- A stone
'#' - A stationary obstacle
'*' - Empty
'.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
It is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the bottom of the box.
Return an n x m matrix representing the box after the rotation described above.
Example 1:

Input: boxGrid = [["#",".","#"]]
Output: [["."],
["#"],
["#"]]
Example 2:

Input: boxGrid = [["#",".","*","."],
["#","#","*","."]]
Output: [["#","."],
["#","#"],
["*","*"],
[".","."]]
Example 3:

Input: boxGrid = [["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]]
Output: [[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]]
Constraints:
m == boxGrid.lengthn == boxGrid[i].length1 <= m, n <= 500boxGrid[i][j]is either'#','*', or'.'.
Solution
Approach: Rotate, Then Drop Stones With a Queue
First build the rotated matrix by copying boxGrid[i][j] to ans[j][m - 1 - i]. After the rotation gravity points down, so stones only move inside their own column.
Handle each column from the bottom up, with a queue of empty rows seen since the last obstacle:
- Empty cell: push its row.
- Obstacle: clear the queue, since stones cannot pass it.
- Stone: if the queue is not empty, move the stone to the front of the queue (the lowest empty row), and push the cell it left, which is now empty.
Complexity: O(mn) time and O(mn) space for the rotated matrix.
from collections import deque
class Solution:
def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
m, n = len(boxGrid), len(boxGrid[0])
ans = [[None] * m for _ in range(n)]
for i in range(m):
for j in range(n):
ans[j][m - i - 1] = boxGrid[i][j]
for j in range(m):
q = deque()
for i in range(n - 1, -1, -1):
if ans[i][j] == "*":
q.clear()
elif ans[i][j] == ".":
q.append(i)
elif q:
ans[q.popleft()][j] = "#"
ans[i][j] = "."
q.append(i)
return ans