C++: Rotate a table

Turn a table of numbers a quarter turn clockwise.

What to build

A two-dimensional vector made from another one.

Requirements

  • Read the table.
  • Print it after rotating 90 degrees clockwise, with values separated by single spaces.

Input

The first line has r and c. Each of the next r lines has c whole numbers.

Output

c lines, each with r numbers.

Constraints

r and c are from 1 to 20.

Example

Input:

2 2
1 2
3 4

Output:

3 1
4 2

Why it works

Working out where one general element goes gives a single formula for the whole table, so that no special cases are needed.

Examples

Example 1 · Input
2 2
1 2
3 4
Expected output
3 1
4 2
Example 2 · Input
2 3
1 2 3
4 5 6
Expected output
4 1
5 2
6 3

Hints

Hint 1

The new table has c rows and r columns.

Hint 2

The element at row i, column j moves to row j, column r - 1 - i.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int r, c;
    cin >> r >> c;
    vector<vector<int>> grid(r, vector<int>(c));
    for (auto& row : grid) {
        for (int& x : row) cin >> x;
    }
    vector<vector<int>> turned(c, vector<int>(r));
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            turned[j][r - 1 - i] = grid[i][j];
        }
    }
    for (const auto& row : turned) {
        for (size_t j = 0; j < row.size(); j++) {
            cout << row[j] << (j + 1 < row.size() ? " " : "\n");
        }
    }
    return 0;
}

Lesson: Vectors →