Turn the square a quarter turn
MediumStuck?
Show a hintHide the hint
Transpose first, swapping across the main diagonal, then reverse each row. Only swap one side of the diagonal or you undo your own work.
The ideas behind this problem
Next in this lesson
Find it by halvingRotate a square grid 90 degrees clockwise and return it.
Worked example#
For
1 2 3
4 5 6
7 8 9
the answer is
7 4 1
8 5 2
9 6 3
Look at where one row went. The first row 1 2 3 became the last column, top to bottom. The second row became the second column. That is the whole rule: row r becomes column n - 1 - r.
The two step trick#
Working out each value's new home in one go is fiddly and easy to get backwards. There is a much easier route in two passes.
First transpose, which means reflect across the main diagonal, swapping grid[r][c] with grid[c][r]:
1 2 3 1 4 7
4 5 6 -> 2 5 8
7 8 9 3 6 9
Then reverse each row:
1 4 7 7 4 1
2 5 8 -> 8 5 2
3 6 9 9 6 3
Done. Two simple passes instead of one confusing one.
Only swap one side of the diagonal. Loop c from r + 1, not from 0. Swapping every pair swaps each one twice and leaves the grid exactly as it started, which is a maddening bug because the code looks right.
For a counter-clockwise turn#
Transpose, then reverse each column instead. Or reverse the rows first and then transpose. Worth knowing, because the question is often asked the other way round.
The cost#
Time O(n squared), since every cell is touched a constant number of times, and there are n squared of them. Memory O(1): the swaps happen in place, with no second grid.
Constraints#
1 <= n <= 200, and the grid is always square-1000 <= value <= 1000
Input
matrix is a row count, then a column count, then the values row by row.
Output
The rotated grid, one row per line, values separated by spaces.
Examples
Input
3 3 1 2 3 4 5 6 7 8 9
Output
7 4 1 8 5 2 9 6 3
The first row 1 2 3 becomes the last column, read downwards.
Input
2 2 1 2 3 4
Output
3 1 4 2
A two by two turns the same way.
Input
1 1 1
Output
1
A single cell is unchanged by any rotation.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.