Problem
You are given an m x n
matrix of characters box
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 box
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.
Examples
Solution
Method 1 - Run the simulation
Rotate the Box by 90 Degrees Clockwise:
- Create a new matrix
ans
with dimensions[n][m]
wheren
is the number of original columns andm
is the number of original rows. - For each element in the original matrix
box
, place it in the new matrixans
such that the row becomes the new column index and the column becomes(m - 1) - row index
.
- Create a new matrix
Apply Gravity:
- For each column
j
in the original matrix, simulate the effect of gravity. - The variable
last
is used to keep track of the last empty position where a stone can fall. - Processing starts from the bottommost row and goes upwards:
- If an obstacle
*
is encountered, setlast
to the row just above the obstacle. - If a stone
#
is encountered, move it tolast
and updatelast
to the position just above. - Continue until all cells in the column are processed.
- If an obstacle
- For each column
Code
Java
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length;
int n = box[0].length;
char[][] ans = new char[n][m];
// Rotate the box by 90 degrees clockwise
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans[j][m - i - 1] = box[i][j];
}
}
// Apply gravity
for (int j = 0; j < m; j++) {
int last = n - 1;
for (int i = n - 1; i >= 0; i--) {
char ch = ans[i][j];
if (ch == '.') {
continue;
}
if (ch == '*') {
last = i - 1;
}
if (ch == '#') {
ans[i][j] = '.';
ans[last][j] = '#';
last--;
}
}
}
return ans;
}
}
Python
class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
m, n = len(box), len(box[0])
ans = [['.'] * m for _ in range(n)]
# Rotate the box by 90 degrees clockwise
for i in range(m):
for j in range(n):
ans[j][m - i - 1] = box[i][j]
# Apply gravity
for j in range(m):
last = n - 1
for i in range(n - 1, -1, -1):
ch = ans[i][j]
if ch == '.':
continue
if ch == '*':
last = i - 1
if ch == '#':
ans[i][j] = '.'
ans[last][j] = '#'
last -= 1
return ans
Complexity
- ⏰ Time complexity:
O(m * n)
, as each cell in the matrix is visited and updated exactly once. - 🧺 Space complexity:
O(n * m)
as a new matrix of size[n][m]
is created to store the rotated box.