|
| 1 | +## 566. Reshape the Matrix |
| 2 | + |
| 3 | +In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. |
| 4 | + |
| 5 | +You're given a matrix represented by a two-dimensional array, and two **positive** integers **r** and **c** representing the **row** number and **column** number of the wanted reshaped matrix, respectively. |
| 6 | + |
| 7 | +The reshaped matrix need to be filled with all the elements of the original matrix in the same **row-traversing** order as they were. |
| 8 | + |
| 9 | +If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. |
| 10 | + |
| 11 | +**Example 1:** |
| 12 | +<pre> |
| 13 | +<b>Input:</b> |
| 14 | +nums = |
| 15 | +[[1,2], |
| 16 | + [3,4]] |
| 17 | +r = 1, c = 4 |
| 18 | +<b>Output:</b> |
| 19 | +[[1,2,3,4]] |
| 20 | +<b>Explanation:</b> |
| 21 | +The <b>row-traversing</b> of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill |
| 22 | +it row by row by using the previous list. |
| 23 | +</pre> |
| 24 | + |
| 25 | +**Example 2:** |
| 26 | +<pre> |
| 27 | +<b>Input:</b> |
| 28 | +nums = |
| 29 | +[[1,2], |
| 30 | + [3,4]] |
| 31 | +r = 2, c = 4 |
| 32 | +<b>Output:</b> |
| 33 | +[[1,2], |
| 34 | + [3,4]] |
| 35 | +<b>Explanation:</b> |
| 36 | +There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original |
| 37 | +matrix. |
| 38 | +</pre> |
| 39 | + |
| 40 | +**Note:** |
| 41 | + |
| 42 | +1. The height and width of the given matrix is in range [1, 100]. |
| 43 | +2. The given r and c are all positive. |
0 commit comments