566. Reshape the Matrix (Leetcode)

PHOTO EMBED

Thu Oct 07 2021 11:43:56 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

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;
    }
};
content_copyCOPY

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

https://leetcode.com/problems/reshape-the-matrix/