In MATLAB, there is a handy function called reshape
which can reshape an mxn
matrix into a new one with a different size rxc
keeping its original data.
You are given an mxn
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 elemetns 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.
Input : mat = [[1,2],[3,4]], r = 1, c = 4
Output : [[1,2,3,4]]
input = [[1,2],[3,4]], r = 2, c = 4
Output : [[1,2],[3,4]]
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
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
elif m == r and n == c :
return mat
row = 0
column = 0
result = [[0]*c for _ in range(r)]
for i in range(m) :
for j in range(n) :
result[row][column] = mat[i][j]
column += 1
if column == c :
row += 1
column = 0
return result