---
# System prepended metadata

title: 566. Reshape the Matrix
tags: [Leetcode, python, array, c++, easy]

---

###### tags: `Leetcode` `easy` `array` `python` `c++`

# 566. Reshape the Matrix

## [題目連結:] https://leetcode.com/problems/reshape-the-matrix/

## 題目:
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.

![](https://i.imgur.com/FkF2tGP.png)

#### [圖片來源:]https://leetcode.com/problems/reshape-the-matrix/


## 解題想法:

先逐一塞滿橫的每一行，再將其添加到列中

## Python:  time:O(mn) space:O(1)
``` python=
class Solution(object):
    def matrixReshape(self, mat, r, c):
        """
        :type mat: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        m=len(mat)
        n=len(mat[0])
        if m*n!=r*c:
            return mat
        row=[]
        col=[]
        #input
        for i in range(m):
            for j in range(n):
                col.append(mat[i][j])
                if len(col)==c:
                    row.append(col)
                    col=[]
        return row
    
if __name__ == '__main__':
    result = Solution()
    mat = [[1,2],[3,4]]
    r = 2
    c = 2
    ans = result.matrixReshape(mat,r,c)
    print(ans)
```

## C++:
``` cpp=
#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int m=mat.size();
        int n=mat[0].size();
        vector<vector<int>> row;
        vector<int> col;
        if (m*n!=r*c)
            return mat;
        for (int i=0; i<mat.size(); i++){
            for (int j=0; j<mat[0].size(); j++){
                col.push_back(mat[i][j]);
                if (col.size()==c){
                    row.push_back(col);
                    col.clear();
                }
            }
        }
        return row;
    }
};

int main(){
    Solution res;
    vector<vector<int>> mat={{1,2},{3,4}};
    int r=1,c=4;
    vector<vector<int>> ans=res.matrixReshape(mat,r,c);
    
    //output ans array
    for (int i=0; i<ans.size(); i++){
        cout<<"[";
        for (int j=0; j<ans[0].size(); j++){
            cout<<ans[i][j]<<" ";
        }
        cout<<"]"<<endl;
    }
    return 0;
}

```