1517. Half a Turn
An R by C grid is given. Turn it a HALF turn, which is two quarter turns
in either direction, and print the result.
The shape does not change. A half turn of an R by C grid is R by C,
which is what makes this the one rotation that can be done inside the input
itself.
1 2 3 -> 6 5 4
4 5 6 3 2 1
1 2 3 -> 9 8 7
4 5 6 6 5 4
7 8 9 3 2 1
1 2 3 4 5 -> 5 4 3 2 1 a single row is simply reversed
## What most people try first
Two passes, each a quarter turn. Correct, and it allocates two grids for an
answer that needs none, and on a rectangle the intermediate shape is C by
R, so the storage has to change twice.
The other reflex is the one-liner out[i][j] = g[R-1-i][C-1-j] applied IN
PLACE. Run over every cell, that swaps each pair twice and returns the grid to
exactly where it started. On the 3 by 3 example the output is the input.
## Read the grid as one long line
Reading row by row, the cell at (i, j) sits at flat position i * C + j. A
half turn sends (i, j) to (R-1-i, C-1-j), whose flat position is
(R-1-i) * C + (C-1-j) = R*C - 1 - (i*C + j)
so a half turn is exactly REVERSING the flattened grid.
n = R * C
for p in 0 .. n/2 - 1:
swap flat[p] and flat[n-1-p]
## Why the loop stops at n / 2
Each iteration handles a PAIR, so running to n would swap every pair a second
time and undo the work. When n is odd the middle position p = (n-1)/2 is
its own partner and needs no swap at all, which integer division already
excludes. The 3 by 3 example, with n = 9, is where that shows.
## Why flattening is legitimate here
Row-major storage means the grid IS a line; the row and column split is an
interpretation of one index. Any operation that maps flat position p to
n - 1 - p can therefore ignore the shape entirely, which is why this rotation
needs no case for a single row or a single column.
## Overflow
Nothing is combined and values fit in a signed 32 bit integer, whose limit is
2147483647. R * C reaches 10^6 and fits easily.
## Cost
O(R C) time with O(1) extra memory beyond the grid. Problems 1515 and 1516
cannot manage that, because their answers are a different shape.
Constraints - `1 ≤ R ≤ 1000` - `1 ≤ C ≤ 1000` - `-10^9 ≤ each value ≤ 10^9` - `R` and `C` are independent; the grid need not be square
Input
The first line contains two integers R and C.
Each of the next R lines contains C integers.
Output
Print the turned grid as R lines of C integers each, separated by single spaces. The shape is unchanged by a half turn.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.