Reshape the Matrix
Given an m x n matrix, reshape it to r x c. If not possible (i.e. ), return the original matrix.
Implement reshape(matrix, r, c), which returns the new matrix as a list of r rows. Elements keep their row-major order: read the original left to right, top to bottom, and fill the new matrix in the same order.
Output each row on a line, space-separated.
Example
1,2 3,4 1 4
1 2 3 4
matrixis a grid: the first row holds and the second row holds . The last input line is the target shape, row and columns.- A reshape never adds or drops values, so it is only possible when the element counts agree: and . They match, so the reshape happens.
- The values keep their row-major reading order (left to right across the first row, then the second), giving the sequence . The new grid is filled in that same order, values per row, so all four land in the single row.
- The result is one row, printed as
1 2 3 4. - Notice what happens with a target of : that needs elements but only exist, so the original matrix comes back unchanged and prints as
1 2and3 4on two lines.
Constraints
- 1 <= m, n <= 100