In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

&nbsp;
Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]


Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]


&nbsp;
Constraints:


	m == mat.length
	n == mat[i].length
	1 &lt;= m, n &lt;= 100
	-1000 &lt;= mat[i][j] &lt;= 1000
	1 &lt;= r, c &lt;= 300


import numpy
class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat
class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {

        if (r * c != mat.length * mat[0].length) {
            return mat;
        }

        int[][] ans = new int[r][c];

        int i = 0;
        int j = 0;

        for(int k = 0; k < mat.length; k++) {
            for(int l = 0; l < mat[0].length; l++) {
                if (j == c) {
                    i++;
                    j = 0;
                }
                ans[i][j++] = mat[k][l];
            }
        }
        return ans;
    }
}
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        if(mat.size()* mat[0].size()!= r * c) {
            return mat;
        } 
        vector<vector<int>>v(r,vector<int>(c));
        int k = 0;
        int l = 0;

        for(int i = 0; i < mat.size(); i++) {
            for(int j = 0; j < mat[0].size(); j++) {
                if(l == v[0].size()) {
                    l = 0;
                    k++;
                }

                v[k][l++] = mat[i][j];
            }
        }
        return v;
    }
};
var matrixReshape = function(mat, r, c) {
  const origR = mat.length;
  const origC = mat[0].length;
  
  if (r*c !== origR*origC) {
    return mat;
  }
  
  const flat = mat.flatMap(n => n);
  
  const output = [];
  for (let i=0; i<flat.length; i++) {
    if (i%c === 0) {
      output.push([]);
    }
    
    output[output.length-1].push(flat[i]);
  };
  return output;
};
Reshape the Matrix