230. Reshape the Tray
A bakery arranges cookies on a tray as the grid grid. The baker wants to move them onto a different tray that has r rows and c columns, keeping the cookies in reading order: the cookies are read row by row, left to right, from the old tray, and placed in the same order onto the new tray, filling its first row, then its second row, and so on.
If the new tray has exactly as many places as the old tray has cookies, return the new arrangement. If the numbers do not match, the move is impossible and you must return the original grid unchanged.
Example 1
- Input:
- grid = [[1,2,3],[4,5,6]], r = 3, c = 2
- Output:
- [[1,2],[3,4],[5,6]]
- Explanation:
There are 6 cookies and the new tray has 3 x 2 = 6 places. Reading order 1,2,3,4,5,6 fills the rows [1,2], [3,4], [5,6].
Example 2
- Input:
- grid = [[7,8,9]], r = 2, c = 2
- Output:
- [[7,8,9]]
- Explanation:
There are 3 cookies but the new tray has 4 places, so the original grid is returned.
Example 3
- Input:
- grid = [[1,2],[3,4],[5,6]], r = 1, c = 6
- Output:
- [[1,2,3,4,5,6]]
- Explanation:
All 6 cookies fit in one long row, in reading order.
Constraints
1 ≤ grid.length, grid[0].length ≤ 100
-1000 ≤ grid[i][j] ≤ 1000
1 ≤ r, c ≤ 300
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(m × n)
- Space
- O(r × c)