Reshape the Matrix in C++


In different platform there is very useful function called 'reshape', that function is used to reshape a matrix into a new one with different size but data will be same. So, if we have a matrix and two values r and c for the row number and column number of the wanted reshaped matrix, respectively.

So, if the input is like [[5,10],[15,20]], row = 1 and col = 4, then the output will be [[5, 10, 15, 20]]

To solve this, we will follow these steps−

  • Define an array temp

  • Define one 2D array res of size (r x c)

  • count := 0

  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −

    • for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −

      • insert nums[i, j] at the end of temp

  • if r * c is not equal to size of nums, then −

    • return nums

  • for initialize i := 0, when i < r, update (increase i by 1), do −

    • for initialize j := 0, when j < c, update (increase j by 1), do −

      • count = count + 1

      • res[i, j] := temp[count]

  • return res

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto>> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
      vector<int> temp;
      vector<vector<int> > res(r, vector<int>(c));
      int count = 0;
      for (int i = 0; i < nums.size(); i++) {
         for (int j = 0; j < nums[0].size(); j++) {
            temp.push_back(nums[i][j]);
         }
      }
      if (r * c != nums.size() * nums[0].size())
         return nums;
      for (int i = 0; i < r; i++) {
         for (int j = 0; j < c; j++) {
            res[i][j] = temp[count++];
         }
      }
      return res;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{5,10},{15,20}};
   print_vector(ob.matrixReshape(v, 1, 4));
}

Input

{{5,10},{15,20}}, 1, 4

Output

[[5, 10, 15, 20, ],]

Updated on: 11-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements