Reshape the Matrix

C++ Solution | Easy to understand | 12ms | 11.4 MB

  • If the number of elements in the original matrix is not equal to the number of elements in the reshaped matrix then simply return the original matrix.
  • If above is not the case then, store all the elements of the original matrix in a vector.
  • And then store the elements in the resultant matrix according to the values of r & c given.
  • Return the resultant matrix.
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int rows=mat.size();
        int cols=mat[0].size();
        if((r*c)!=(rows*cols)){
            return mat;
        }
        vector<int>temp;
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                temp.push_back(mat[i][j]);
            }
        }
        int idx=0;
        vector<vector<int>>ans;
        for(int i=0;i<r;i++){
            vector<int>res;
            for(int j=0;j<c;j++){
                res.push_back(temp[idx]);
                idx++;
            }
            ans.push_back(res);
        }
        return ans;
    }
};

Happy Coding!!!

Comments (0)