Why it works
- A quarter turn sends the cell (r, c) to (c, n - 1 - r). Applied four times it comes back, so the cells split into cycles of four: one on each side of the same ring, the same distance from a corner.
- In a cycle each cell takes the value of the one behind it, so only the first value written over has to be kept aside: tmp holds the top cell until the right cell takes it.
- i runs from layer to last - 1, not to last: the corner at the end of a side is the start of the next side, and it already moved in the first cycle. One more step would turn it back.
Complexity
Time O(n²): every cell is moved once. Memory O(1): one spare variable, tmp, no second matrix.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗