Rotate 90°
Completed
Read an n×n matrix and print it rotated 90° clockwise.
Input
n, then n rows.
Output
n rows.
Example
Input
3 1 2 3 4 5 6 7 8 9
Output
7 4 1 8 5 2 9 6 3
Editor
C++
Hints
Row i of the result is column i of the original, read bottom to top.
Solution explanation
The new cell (i, j) comes from the old cell (n−1−j, i).
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<vector<int>> m(n, vector<int>(n));
for (auto &row : m)
for (int &x : row) cin >> x;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << m[n - 1 - j][i] << (j < n - 1 ? " " : "\n");
}
}
return 0;
}