Description
Given a 2D matrix mat and two integers r and c, reshape the matrix to have r rows and c columns. If reshape is not possible, return the original matrix.
Examples
Input:
mat = [[1,2],[3,4]], r = 1, c = 4Output:
[[1,2,3,4]]Explanation:
Reshape 2x2 to 1x4.
Input:
mat = [[1,2,3,4,5,6]], r = 2, c = 3Output:
[[1,2,3],[4,5,6]]Explanation:
Reshape 1x6 matrix to 2x3. Elements are filled row by row: first row gets [1,2,3], second row gets [4,5,6].
Input:
mat = [[1,2,3],[4,5,6],[7,8,9]], r = 1, c = 2Output:
[[1,2,3],[4,5,6],[7,8,9]]Explanation:
Cannot reshape 3x3 matrix (9 elements) to 1x2 (2 elements) since total elements don't match. Return original matrix unchanged.
Constraints
- •
1 ≤ m, n ≤ 100