✅ Reshape the Matrix || CPP/C++ || Implementation and Explanation
Solution 1\n1. The simple and brute force way is to put all the matrix elements into the 1D array.\n2. Create a 2D aray of size rXc and initialize with 0 & push
**Solution 1**\n1. The simple and brute force way is to put all the matrix elements into the 1D array.\n2. Create a 2D aray of size rXc and initialize with 0 & push all the elements of 1D array\ninto the new matrix\n* And, by the way the base condition is something very intuitive. Just think about for a sec.\nif `m*n != r*c` then it is clear that new matrix can\'t accommodate all elements, so just\nreturn the same matrix otherwise calculate the calculate the new one.\n```\nclass Solution {\npublic:\n    //Time: O(mxn + rxc), Space: O(sizeof(oneDArray) + rxc)\n    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n        int m = mat.size();\n        int n = mat[0].size();\n\n        //base condition\n        if(m*n != r*c) return mat;\n        \n        //convert the matrix to 1d array\n        vector<int> oneDArray;\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                oneDArray.push_back(mat[i][j]);\n            }\n        }\n        \n        //put all the elements from 1d array to new matrix\n        vector<vector<int>> newMatrix(r, vector<int>(c, 0));\n        int idx=0;\n        for(int i=0; i<r; i++){\n            for(int j=0; j<c; j++){\n                newMatrix[i][j] = oneDArray[idx];\n                idx++;\n            }\n        }\n        return newMatrix;\n    }\n};\n```\n\n**Solution 2**\nAnother method is like one pass of the current matrix, and create new matrix initialize with \n0, put the previous elements into the new matrix according to the rxc dimension.\nRemember the base condition from the previous solution, we need to apply here also.\n```\nclass Solution {\npublic:\n    //Time: O(mxn), Space: O(rxc)\n    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n        int m = mat.size();\n        int n = mat[0].size();\n        \n        //base condition\n        if(m*n != r*c) return mat;\n        \n        //creating the new matrix with rxc dimension\n        vector<vector<int>> newMatrix(r, vector<int>(c, 0));\n        \n        //put all the elements to the new matrix\n        int newRow = 0, newColumn = 0;\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                \n                //if newColumn is equal to the c then increase the newRow by 1 and set \n                //newColumn to 0\n                if(newColumn == c){\n                    newRow++;\n                    newColumn = 0;\n                }\n                newMatrix[newRow][newColumn] = mat[i][j];\n                newColumn++;\n            }\n        }\n        return newMatrix;\n    }\n};\n```
['Array', 'C', 'C++']