First, check if the total number of elements m * n is equal to r * c. If not, return the original matrix. Otherwise, flatten the matrix and then rebuild it with new dimensions.
m, n = len(mat), len(mat[0]).- If
m * n != r * c, returnmat. - Initialize
res = [[0] * c for _ in range(r)]. - Iterate through
m * nelements using a single counterk:- Value is at
mat[k // n][k % n]. - Place it at
res[k // c][k % c].
- Value is at
- Return
res.
- Time Complexity: O(M * N).
- Space Complexity: O(R * C) for the result.
def matrix_reshape(mat, r, c):
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
res = [[0] * c for _ in range(r)]
for k in range(m * n):
res[k // c][k % c] = mat[k // n][k % n]
return res