Rotating the Box

You are given an `m x n` matrix of characters `boxGrid` showing a side view of a box. Each cell is a stone `'#'`, a stationary obstacle `'*'`, or empty `'.'`. The box is rotated 90 degrees clockwise, which makes some stones fall. Every stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Obstacles do not move, and the rotation's inertia does not shift stones sideways. It is guaranteed that each stone in `boxGrid` rests on an obstacle, another stone, or the bottom of the box before the rotation. Return an `n x m` matrix showing the box after the rotation.

30:00

Rotating the Box
medium
Free written solution
Topics
Companies

You are given an m x n matrix of characters boxGrid showing a side view of a box. Each cell is a stone '#', a stationary obstacle '*', or empty '.'.

The box is rotated 90 degrees clockwise, which makes some stones fall. Every stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Obstacles do not move, and the rotation's inertia does not shift stones sideways.

It is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the bottom of the box before the rotation.

Return an n x m matrix showing the box after the rotation.

Example 1:
Input: {"boxGrid":[["#",".","#"]]}
Output: [["."],["#"],["#"]]
Constraints:
  • m==boxGrid.lengthm == \text{boxGrid.length}

  • n==boxGrid[i].lengthn == \text{boxGrid}[i].\text{length}

  • 1≤m,n≤5001 \leq m, n \leq 500

  • boxGrid[i][j]\text{boxGrid}[i][j] is either '#', '*', or '.'

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"boxGrid":[["#",".","#"]]}

The box lies on its side. Rotating it clockwise turns each row into a column whose bottom is the row's right end, so first slide every stone to the right within its row.

1. box on its side: gravity pulls stones to the green wall on the right

gold = cell being scanned

blue dashes = empty, where the next stone lands

2. rotated 90 degrees clockwise (3 x 1): input column c, bottom row first, becomes output row c

built after every row has settled

Variables
VariableValue
m1
n3
DepthFunction Call
Stack empty
0/7