Skip to content

Commit dbbe530

Browse files
authored
Merge pull request #783 from ishikasinha-d/rotate-by-90
Create rotate_by_90.cpp
2 parents eac3a2b + cdeffe6 commit dbbe530

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

2D Arrays/rotate_by_90.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Given a square matrix of size N x N. The task is to rotate it by 90 degrees in anti-clockwise direction without using any extra space.
2+
3+
#include<bits/stdc++.h>
4+
#include <stdio.h>
5+
using namespace std;
6+
7+
int main()
8+
{
9+
int t; cin>>t;
10+
11+
while(t--)
12+
{
13+
int n;
14+
cin>>n;
15+
int matrix[n][n];
16+
17+
for(int i = 0; i < n; i++)
18+
{
19+
for(int j = 0; j < n; j++)
20+
{
21+
cin>>matrix[i][j];
22+
}
23+
}
24+
25+
//rotating the matrix by 90 , anticlockwise
26+
// the matrix will have floor(n/2) cycles
27+
for(int i=0; i<n/2; i++)
28+
{
29+
//parsing through each cycle and rotating
30+
for(int j=i; j< n-i-1; j++)
31+
{
32+
//stored current element in temporary variable temp
33+
int temp= matrix[i][j];
34+
35+
//shifted right element to top
36+
matrix[i][j]= matrix[j][n-i-1];
37+
38+
//shifted bottom element to right
39+
matrix[j][n-i-1]= matrix[n-1-i][n-1-j];
40+
41+
//shifted left element to bottom
42+
matrix[n-1-i][n-1-j] = matrix[n-1-j][i];
43+
44+
//assign temp to left
45+
matrix[n-1-j][i]= temp;
46+
}
47+
}
48+
49+
for(int i = 0; i < n; i++)
50+
for(int j=0; j<n; j++)
51+
cout<< matrix[i][j];
52+
cout<<endl;
53+
}
54+
return 0;
55+
}

0 commit comments

Comments
 (0)