# Rotation of a square matrix by 90 degrees in c++

In this tutorial, we will learn how to rotate a square matrix by 90 degrees in c++. There are various ways to rotate a square matrix by 90 degrees(We will learn other ways in other articles). Below is an interesting solution on the rotation of a square matrix in C++. A square matrix is a matrix in which the rows and columns are equal. Rotation by 90 degrees means:

Input:

1 2 3 4 5 6 7 8 9

Output:

7 4 1 8 5 2 9 6 3

## Algorithm of how to rotate a square matrix by 90 degrees in C++

The way we will be using is by creating a new matrix.

- Create a new matrix b[][].
- Map the indexes of a to b by rotation. For example, in the above example: 1 in matrix A is at i=0 and j=0 and in matrix b, it will be at i=0 and j=2.
- Similarly, 4 element in matrix A is at i=1 and j=0 and in matrix b, it will be at i=0 and j=1.
- Find out all the corresponding indexes like this.

Below is the figure, The new indexes are represented by pink ink. i is the rows and j is the columns.

Now, look at this part of the code.

for(int col=0;col<n;col++) { int x=0; for(int row=n-1;row>=0;row--) { b[col][x]=a[row][col]; x++; } }

In the first pass, `b[0][0]=a[2][0]`

(copies the element 7)

In the second pass,x increases by 1. `b[0][1]=a[1][0]`

(copies the element 4)

Similarly, the rest of the elements get copied to matrix b.

Here is the rest of the code:

#include<bits/stdc++.h> using namespace std; void rotate(int a[][10], int n, int b[][10]) { for (int colofmatrix = 0; colofmatrix < n; colofmatrix++) { int x = 0; for (int rowofmatrix = n - 1; rowofmatrix >= 0; rowofmatrix--) { b[colofmatrix][x] = a[rowofmatrix][colofmatrix]; x++; } } } int main() { int rowofmatrix, colofmatrix, n, a[10][10]; int b[10][10]; //creating a temporary array cin >> n; //enter number of rows and cols for (rowofmatrix = 0; rowofmatrix < n; rowofmatrix++) { for (colofmatrix = 0; colofmatrix < n; colofmatrix++) { cin >> a[rowofmatrix][colofmatrix]; } } rotate(a, n, b); for (rowofmatrix = 0; rowofmatrix < n; rowofmatrix++) { for (colofmatrix = 0; colofmatrix < n; colofmatrix++) { cout << b[rowofmatrix][colofmatrix] << '\t'; } cout << endl; } }

Input:

3 1 2 3 4 5 6 7 8 9

Output:

7 4 1 8 5 2 9 6 3

Input: 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Output:

13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4

The auxiliary space used here is O(n) and time complexity is O(n*n).

If you like this post, please comment below and also refer to:

Find maximum square sub matrix with all 1’s

## Leave a Reply