Turn a table of numbers a quarter turn clockwise.
What to build
A program that prints a 2D array rotated by 90 degrees clockwise.
Requirements
- Read a matrix with
rrows andccolumns. - Print the rotated matrix, which has
crows andrcolumns. - Separate the numbers in a row with single spaces.
Input
The first line has r and c. Each of the next r lines has c numbers.
Output
c lines, each with r numbers.
Constraints
1 ≤ r, c ≤ 10.
Example
Input:
2 3
1 2 3
4 5 6
Output:
4 1
5 2
6 3
Why it works
After a quarter turn clockwise, the left column becomes the top row, read from the bottom up. Working out which old cell lands in each new cell is the same index arithmetic that row-major order uses.
Examples
Example 1 · Input
2 3 1 2 3 4 5 6
Expected output
4 1 5 2 6 3
Example 2 · Input
1 1 9
Expected output
9
Hints
Hint 1
The result has c rows and r columns.
Hint 2
Row i of the result is column i of the original, read from the bottom row up to the top.
Hint 3
So the item at row i, column j of the result is m[r - 1 - j][i].
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int r, c, m[10][10];
scanf("%d %d", &r, &c);
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++) scanf("%d", &m[i][j]);
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
if (j > 0) printf(" ");
printf("%d", m[r - 1 - j][i]);
}
printf("\n");
}
return 0;
}