class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) { vector<vector<int>>ans(r,vector<int>(c)); int n = mat.size(), m = mat[0].size(); if(n*m != r*c) return mat; int p = 0, q = 0; for(int i = 0; i < r; ++i) { for(int j = 0; j < c; ++j) { ans[i][j] = mat[p][q]; q = (q + 1) % m; if(q == 0) p = p + 1; } } return ans; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter