A nice two pointer problem
1 min readSep 10, 2021
Rotate a Box Under Gravity
We can solve the problem by using two pointers. For each row, we use two pointers:
- left and right
- left indicate the box we shoud move
- right indicate the available location to be moved.
Code
vector<vector<string>> rotate(vector<vector<string>>& matrix){
const int n = matrix.size(), m = matrix[0].size();
vector<vector<string>> newmatrix(m, vector<string>(n));
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
newmatrix[j][n-i-1] = matrix[i][j];
}
}
return newmatrix;
}vector<vector<string>> solve(vector<vector<string>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return matrix;
const int n = matrix.size(), m = matrix[0].size();
for (int i = 0; i < n; ++i){
int l = m -1, r = m -1;
while (l >= 0){
if (matrix[i][l] == "*"){
l = r - 1;
r = r - 1;
} else if (matrix[i][l] == "."){
l--;
} else {
swap(matrix[i][l], matrix[i][r]);
l--;r--;
}
}
}
return rotate(matrix);
}