[LeetCode] Rotating the Box

1861. Rotating the Box

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& A) {
int n = A.size(), m = A[0].size();
for(int i = 0; i < n; i++) {
int l = m - 1, r = m - 1,c = 0;
while(l >= 0) {
int s = 0;
while(l >= 0 and A[i][l] != '*') {
if(A[i][l--] == '#') s++;
}
while(s--) A[i][r--] = '#';

while(r > l) A[i][r--] = '.';

r = l = l - 1;
}
}
vector<vector<char>> res(m, vector<char>(n));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
res[i][j] = A[n-j-1][i];
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/02/PS/LeetCode/rotating-the-box/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.