Reshape a matrix into a new size while preserving the original row-major order of its elements.
Problem
Given an matrix, reshape it into a new matrix with dimensions .
The reshaping must keep the elements in the same row-major order as the original matrix. If the reshape is not possible because the total number of elements does not match, return the original matrix unchanged.
Notes
- Elements must be read left to right, top to bottom.
- The new matrix should also be filled left to right, top to bottom.
- If , no valid reshape exists.
Input Format
- A 2D integer matrix
mat - Two integers
randcrepresenting the desired number of rows and columns
Output Format
- Return the reshaped matrix if possible
- Otherwise return the original matrix
Constraints
1 <= m, n <= 1001 <= r, c <= 100- The matrix contains integers
- The total number of elements may or may not match the requested shape
Example 1
Input
mat = [[1,2],[3,4]], r = 1, c = 4
Output
[[1,2,3,4]]
Explanation
The matrix has 4 elements, and , so reshaping is valid. The row-major order is preserved.
Example 2
Input
mat = [[1,2],[3,4]], r = 2, c = 3
Output
[[1,2],[3,4]]
Explanation
The matrix has 4 elements, but , so reshaping is impossible. Return the original matrix.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.