Matrix Reshape

Easy~10 min

Given an m x n matrix and two integers r and c representing the number of rows and columns of the desired reshaped matrix, reshape the matrix to have r rows and c columns.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation is not possible (i.e., m * n != r * c), return the original matrix unchanged.

Examples

Example 1
Input: matrix = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Explanation: The 2x2 matrix is reshaped into a 1x4 matrix by reading elements row by row.
Example 2
Input: matrix = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Explanation: 2 * 4 = 8 != 2 * 2 = 4, so the reshape is not possible. Return the original matrix.
Example 3
Input: matrix = [[1,2,3,4,5,6]], r = 2, c = 3
Output: [[1,2,3],[4,5,6]]
Explanation: The 1x6 matrix is reshaped into a 2x3 matrix.

Constraints

  • 1 <= m, n <= 100
  • -1000 <= matrix[i][j] <= 1000
  • 1 <= r, c <= 300
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run