Amaarockz
Amaarockz

Reputation: 4684

Transpose a 2D vector matrix

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

Upvotes: 0

Views: 733

Answers (1)

Amaarockz
Amaarockz

Reputation: 4684

Below is the code for inplace(Fixed space) || n*n matrix

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int i,j,n=matrix.size();
        for(i=0; i<n; i++) {
            // Instead of j starting with 0 every time, its needs to start from i+1
            for(j=i+1; j<n; j++) {
                swap(matrix[i][j], matrix[j][i]);
            }
        }
        for(int i=0; i<n;i++) {
            reverse(matrix[i].begin(), matrix[i].end());
        }
    }
};

Upvotes: 1

Related Questions