Intuition
Rotating the box clockwise turns each row into a column. Stones fall to the right within each row (because right becomes down after rotation). So we can simulate gravity in the original orientation, then rotate.
Explanation
Approach
- For each row in
boxGrid, slide stones to the right within their obstacle-bounded segments:- Walk right-to-left with a write pointer
wpinitialised to the column index. - On
'#': move it towp, decrementwp. - On
'*': resetwpto the cell just to the left of the obstacle. - On
'.': skip.
- Walk right-to-left with a write pointer
- Rotate the result 90° clockwise: cell
(i, j)of the input becomes cell(j, m - 1 - i)of the output.
Complexity
- Time:
O(m · n)— each cell visited a constant number of times. - Space:
O(m · n)— the rotated output grid.
Implementation
import java.util.*;
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length, n = box[0].length;
// Apply gravity: stones fall to the right
for (int i = 0; i < m; i++) {
int wp = n - 1;
for (int j = n - 1; j >= 0; j--) {
if (box[i][j] == '*') {
wp = j - 1;
} else if (box[i][j] == '#') {
box[i][j] = '.';
box[i][wp] = '#';
wp--;
}
}
}
// Rotate 90 degrees clockwise
char[][] rotated = new char[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rotated[j][m - 1 - i] = box[i][j];
}
}
return rotated;
}
}