-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
61 lines (55 loc) · 1.98 KB
/
Solution.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <cstddef>
#include <cstdlib>
#include <vector>
class Solution {
private:
static constexpr char STONE = '#';
static constexpr char OBSTACLE = '*';
static constexpr char EMPTY = '.';
public:
std::vector<std::vector<char>> rotateTheBox(
std::vector<std::vector<char>>& box) {
// Hm. Seems like two pointers. The output dimensions is a transpose of the
// input.
//
// Initialize the output n x m.
// Then, initialize two pointers i_in, i_out, to the last position of the
// first row and the last position of the first column respectively.
//
// Check i_in. If i_in is a stone, move the stone to i_out, advance both
// pointers.
// If i_in is a obstacle, then advance i_out to the corresponding index of
// i_in in the output, where if i_in = (r, c), then i_out = (c, r), i.e.,
// move i_out to the column pointed to by i_in.
// If i_in is an empty space, then advance i_in only.
//
// Repeat for all columns in the new output.
// Tricky(?) part is the rotation.
// (r, c) --rotate 90degrees-> (c, m - 1 - r)
const size_t rows = box.size();
const size_t cols = box[0].size();
std::vector<std::vector<char>> rotated(cols,
std::vector<char>(rows, EMPTY));
// for each row in the input grid (which corresponds to the columns in the
// output grid)
for (int r = 0; r < rows; ++r) {
int writeRow = cols - 1;
for (int c = cols - 1; c >= 0; --c) {
if (box[r][c] == STONE) {
// 90 degrees: (r, c) --> (c, rows - 1 - r)
rotated[writeRow][rows - 1 - r] = STONE;
--writeRow;
continue;
}
if (box[r][c] == OBSTACLE) {
// Obstacles stay in the rotated position.
rotated[c][rows - 1 - r] = OBSTACLE;
writeRow = c - 1;
}
// EMPTY case already handled by initialization, just move the read
// pointer, i.e,. --c.
}
}
return rotated;
}
};