Grade 10 · Two-dimensional arrays (matrices)Citește în română

Rotating a matrix by 90 degrees

Original: Rotirea unei matrice cu 90 de grade

O(n²)C++1757 lines2 examples

The idea

When rotating clockwise, the first column read from bottom to top becomes the first row. The result matrix b has m rows and n columns, and the element a[i][j] goes to b[j][n + 1 - i]. We use a second matrix so that we do not overwrite values we have not moved yet.

Original description (Romanian)

La rotirea în sensul acelor de ceasornic, prima coloană citită de jos în sus devine prima linie. Matricea rezultat b are m linii și n coloane, iar elementul a[i][j] ajunge în b[j][n + 1 - i]. Folosim o a doua matrice, ca să nu suprascriem valori pe care încă nu le-am mutat.

Complexity
O(n * m)
Grade
Grade 10 (Clasa a X-a)

Examples

Example 1

Input

2 3
1 2 3
4 5 6

Expected output

4 1
5 2
6 3
Example 2

Input

3 3
1 2 3
4 5 6
7 8 9

Expected output

7 4 1
8 5 2
9 6 3

The code

Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.

rotire-cu-90-de-grade.cpp
/*
 * Titlu: Rotirea unei matrice cu 90 de grade
 * Clasa: 10
 * Capitol: Tablouri bidimensionale (matrice)
 * Descriere: La rotirea în sensul acelor de ceasornic, prima coloană citită de jos
 *            în sus devine prima linie. Matricea rezultat b are m linii și n coloane,
 *            iar elementul a[i][j] ajunge în b[j][n + 1 - i]. Folosim o a doua
 *            matrice, ca să nu suprascriem valori pe care încă nu le-am mutat.
 * Complexitate: O(n * m)
 *
 * Exemplu
 * Intrare:
 * 2 3
 * 1 2 3
 * 4 5 6
 * Ieșire:
 * 4 1
 * 5 2
 * 6 3
 *
 * Exemplu
 * Intrare:
 * 3 3
 * 1 2 3
 * 4 5 6
 * 7 8 9
 * Ieșire:
 * 7 4 1
 * 8 5 2
 * 9 6 3
 */
#include <iostream>
using namespace std;

int a[101][101], b[101][101];

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> a[i][j];

    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            b[j][n + 1 - i] = a[i][j];

    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
            cout << b[i][j] << ' ';
        cout << '\n';
    }
    return 0;
}

Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.