Reshape the Matrix
Core idea: A 2D grid is secretly a 1D array laid down row by row. Number the cells
0, 1, 2, …in reading order — that's the flat indexk. Then(row, col)andkare two views of the same thing:k = row·cols + col, and going back,row = k // cols,col = k % cols. Reshaping is just reading cells out at the old width and writing them back at the new width — no values change, only how you slice the stream.
1. The problem, in a fresh setting
You're handed a strip of photo thumbnails that a gallery exported as a grid: m rows of n images each, stored top-to-bottom, left-to-right. The print shop wants the same photos in the same order but laid out on a different page — r rows of c images. Nothing is added, removed, or reordered; the sequence is identical. You're only rewrapping the stream at a new line width.
That works only if the totals line up: an m × n grid holds m·n photos, and the new layout has room for exactly r·c. If m·n == r·c, refill the new grid in reading order. If they don't match, the reshape is impossible — hand back the original grid untouched.
mat |
r |
c |
Result |
|---|---|---|---|
[[1, 2], [3, 4]] |
1 |
4 |
[[1, 2, 3, 4]] |
[[1, 2, 3, 4]] |
2 |
2 |
[[1, 2], [3, 4]] |
[[1, 2], [3, 4]] |
2 |
4 |
[[1, 2], [3, 4]] (unchanged) |
The third row is the trap: 2·2 = 4 but 2·4 = 8. The cells can't fill a 2×4 grid, so we return the input as-is.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson