I want to rotate a matrix by 90 degrees in place represented in the form of a 1D vector.
When it is in 2D, this is what I did that works:
void rotate(vector<vector<int>>& matrix) {
reverse(matrix.begin(), matrix.end());
for (int i = 0; i < matrix.size(); ++i){
for (int j= i + 1; j < matrix[0].size(); ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
}
When I represent it in 1D, for example:
vector<int> matrix = {1, 2, 3, 4, 5, 6, 7, 8, 9};
This is what I tried:
void rotate(vector<int>& matrix, const int& n) {
int i = 0, j = 0;
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
swap(matrix[i + j], matrix[i + j * n]);
}
reverse(matrix.begin() + i * n, matrix.begin() + (i * n) + j);
}
}
The result was:
matrix = {7, 4, 1, 6, 5, 8, 9, 2, 3}
But the expected result should be:
matrix = {7, 4, 1, 8, 5, 2, 9, 6, 3}
Is there a better way to do this or what am I missing, in terms of indexing?