A mosaic restoration studio stores every panel as a rectangular grid of tile IDs. A client requests that a panel be reflowed into a grid with a different number of rows and columns, without disturbing the reading order of the tiles: read the current panel row by row, left to right and top to bottom, then lay those tiles back down in that exact order into the new grid, again filling it row by row, left to right and top to bottom. If the requested grid does not have exactly the same total number of tiles as the original panel, the reflow cannot be carried out and the panel must be handed back exactly as it started. Given the original panel and the requested dimensions, output the resulting grid.
If r * c equals m * n, print the reflowed panel as r lines of c space-separated integers. Otherwise, print the original panel unchanged, as m lines of n space-separated integers.
Example 1
Input
2 2 1 2 3 4 1 4
Expected
1 2 3 4
Explanation
Reading the 2x2 panel row by row gives the sequence 1, 2, 3, 4. Since the requested grid has 1*4=4 tiles, matching the original 2*2=4, refilling a 1-row by 4-column grid with that same sequence produces a single row: 1 2 3 4.
Example 2
Input
2 2 1 2 2 4 2 4
Expected
1 2 2 4
Explanation
The requested grid needs 2*4=8 tiles, but the panel only has 2*2=4 tiles, so the reflow is impossible. The panel is printed exactly as given: 1 2 on the first line and 2 4 on the second.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →