How to Transpose a 2D Matrix?


Given a 2D Matrix, return the transpose of it.

The transpose of a matrix is the matrix flipped over it’s main diagonal, switching the row and column indices of the matrix.

Example:

1 2 3
4 5 6
7 8 9

The transpose of above matrix should be:

1 2 3
4 5 6

As we can see, ,the rows and columns are swapped.

C++ method to Transpose a 2D Matrix

First of all, we need to allocate the result matrix with rows and columns dimensions swapped. Then, we just need to assign using the indices swapped. The C++ method to swap a 2D matrix (represented by vector) is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& A) {
        int rows = A.size();
        if (rows == 0) return {{}};
        int cols = A[0].size();
        vector<vector<int>> r(cols, vector<int>(rows));        
        for (int i = 0; i < rows; ++ i) {
            for (int j = 0; j < cols; ++ j) {
                r[j][i] = A[i][j];
            }
        }        
        return r;
    }
};
class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& A) {
        int rows = A.size();
        if (rows == 0) return {{}};
        int cols = A[0].size();
        vector<vector<int>> r(cols, vector<int>(rows));        
        for (int i = 0; i < rows; ++ i) {
            for (int j = 0; j < cols; ++ j) {
                r[j][i] = A[i][j];
            }
        }        
        return r;
    }
};

The runtime complexity is O(n^2) and the space complexity is O(n^2) as well.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
241 words
Last Post: VPS Tool/API Server Upgraded to Four Cores!
Next Post: How to Find Top K Frequent Elements via Priority Queue or Sorting?

The Permanent URL is: How to Transpose a 2D Matrix?

Leave a Reply