Reputation: 3
I been trying to write a program to rotate the matrix by 90 degrees either clockwise or counterclockwise, but I am not sure how to do it and when I looked it up online. I see a lot of in place solution which isn't what I intended to do originally. My idea is to create another nxn matrix and just copy value from one matrix to another. below is code:
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
vector<vector<int> > rotate(const vector<vector<int> > &v);
int main(){
vector<vector<int> > vec{{1,1,1},
{2,2,2},
{3,3,3}};
// original
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[0].size(); j++) {
cout << vec[i][j];
}
cout << "\n";
}
cout << "after rotation:\n";
// print matrix after rotation
vector<vector<int> > ans = rotate(vec);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
}
cout << "\n";
}
return 0;
}
vector<vector<int> > rotate(const vector<vector<int> > &v) {
vector<vector<int> > ans;
int height = v.size(), width = v[0].size();
for (int i = 0; i < height; i++) {
vector<int> row;
ans.push_back(row);
for( int j = 0; j < width; j++){
ans.at(i).push_back(0);
}
}
for(int i = 0; i <= height; i++) {
for(int j = 0; j < width; j++) {
//here i deleted my code because it didn't copy the value over correctly!
}
}
return ans;
}
I did a lot of research on how to do a vector(very confusing with & and stuff) and now I been scratching my head trying to come up with a way to copy the value over and there were some strange rotation performed (not 90degrees), so I deleted what I did and hope you would give me some hints on what to do.
So say I have orginal matrix, after 90 degree clockwise rotation.
111 321
222 ==> 321
333 321
Upvotes: 0
Views: 190
Reputation: 1500
So you start with a matrix looking like:
Then you want to index into it with i
and j
, to access a rotated version of it:
So you can see i
goes from n
to 0
and j
goes from 0
to n
. i
is the x axis and j
is the y axis. Because you index into matrices using [y][x]
, you end up with something like this:
vector<vector<int> > rotate(const vector<vector<int> > &v) {
int n = v.size();
// create nxn matrix
vector<vector<int> > ans(n, vector<int>(n));
// copy in the values rotated
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
ans[i][j] = v[j][n - i - 1];
}
}
return ans;
}
Live example here
Upvotes: 2
Reputation: 5826
111 321
222 ==> 321
333 321
Observe that as we iterate through the first row of the first matrix, we want to copy 111 over as the last column of the secondary matrix, and copy 222(second row) over as the second to last column of the secondary matrix and so on. One way of doing this is as so:
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
ans[j][width-1-i] = v[i][j];
}
}
so you have
ans[0][2] = v[0][0]
ans[1][2] = v[0][1]
ans[2][2] = v[0][2]
ans[0][1] = v[1][0]
.....
Upvotes: 1