Problem Description
Given an m x n matrix representing a side-view of a box, where each cell is either a stone ("#"), an obstacle ("*"), or empty ("."). The box is rotated 90 degrees clockwise, and then gravity makes any loose stones fall down until they hit an obstacle, another stone, or the bottom of the box. The obstacles remain in their rotated positions. Return the resulting n x m matrix after the rotation and gravity simulation.
Key Insights
- Rotate the box 90 degrees clockwise by remapping indices: element at (i, j) goes to (j, m-1-i).
- After the rotation, simulate gravity on each column, making stones fall down.
- Use a pointer to track the "available" position (the lowest empty cell) in each column.
- The obstacles act as barriers and reset the available pointer for stones above them.
Space and Time Complexity
Time Complexity: O(mn) because each cell is processed a constant number of times. Space Complexity: O(mn) required for the output (rotated) matrix.
Solution
The approach consists of two major steps:
- Rotate the matrix 90 degrees clockwise by creating a new matrix where the cell originally at (i, j) maps to (j, m-1-i).
- Simulate gravity on the rotated matrix by processing each column from bottom to top. Maintain an "available" pointer that indicates where the next stone ("#") should fall. When an obstacle ("*") is encountered, reset the pointer above the obstacle. Replace stone positions accordingly.