DEV Community

Abdullah Al-Mamun
Abdullah Al-Mamun

Posted on

Reshape the Matrix - leetcode(566)

Problem:
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.

Sample 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Enter fullscreen mode Exit fullscreen mode

Sample 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Enter fullscreen mode Exit fullscreen mode

Idea:

  • If given matrix's row * column != r * c then return given matrix
  • Create a 1d vector temp then store all the element of the matrix into the vector sequentially
  • Run a nested loop from 0 - r and 0 - c then store elements from the 1d vector to your 2d result vector.

Solution 1:

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        vector<int> temp;
        vector<vector<int> > res(r, vector<int>(c));

        int idx = 0;
        if(r * c != mat.size() * mat[0].size()) return mat;
        for(int i=0; i<mat.size(); i++){
            for(int j=0; j<mat[0].size(); j++){
                temp.push_back(mat[i][j]);
            }
        }
        for(int i=0; i<r; i++){
            for(int j=0; j<c; j++){
                res[i][j] = temp[idx++]; 
            }
        }
        return res;
    }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

⬇️ The only reason people scroll to the bottom...

is because they want to read more. Sign up for an account to bookmark, comment, and react to articles that interest you.