Is there a way to find transpose a 2D vector matrix without allocating another 2D vector??
Sample Testcase
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Code that I tried
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int i,j, n=matrix.size(),temp;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
};
Printed Output:
1 2 3
4 5 6
7 8 9
Expected Output:
1 4 7
2 5 9
3 6 9
Edited:
New Code:
class Solution {
public:
void transpose(vector<vector<int>>& mat, int n) {
int i,j,temp;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp;
}
}
}
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size(),i,j;
transpose(matrix, n);
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
};
Thanks in advance
for (j = 0; j < i; j++)<-- notej < inotj < n. It would be very straight forward for you to work through this by hand on paper and work out how your swaps should go. Also, usestd::swapinstead of the 3-line version you're doing.