## 題目要求

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and crepresenting the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

## python代碼

class Solution:

def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:

rows, cols = len(nums), len(nums)

if rows * cols != r * c:

return nums

else:

matrix_list = []

for row in nums:

matrix_list.extend(row)

new_matrix1 = []

new_matrix2 = []

for idx in range(r):

for i in range(0+idx*c,c+idx*c):

new_matrix1.append(matrix_list[i])

new_matrix2.append(new_matrix1)

new_matrix1 = []

return new_matrix2

#### 注意！

© 2014-2022 ITdaan.com 联系我们： 