Skip to content

Commit fd7a0cf

Browse files
committed
added rotate 2D array
1 parent b947cb9 commit fd7a0cf

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Arrays/15. Rotate 2D array.cpp

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
//Rotate anti clockwise by 90 degree
5+
void rotate(int a[][100],int n)
6+
{
7+
for(int row=0;row<n;row++){
8+
int s_c=0; //start column
9+
int e_c=n-1; //end column
10+
if(s_c<e_c){
11+
swap(a[row][s_c],a[row][e_c]);
12+
s_c++;
13+
e_c--;
14+
}
15+
}
16+
17+
//transpose
18+
for(int i=0;i<n;i++){
19+
for(int j=0;j<n;j++){
20+
if(i<j){
21+
swap(a[i][j],a[j][i]);
22+
}
23+
}
24+
}
25+
}
26+
27+
int main()
28+
{
29+
int row=0,col=0;
30+
int a[100][100];
31+
int m,n;
32+
cout<<"Enter row and column"<<endl;
33+
cin>>m>>n;
34+
35+
int val=1;
36+
for(int row=0;row<m;row++){
37+
for(col=0;col<n;col++){
38+
a[row][col]=val;
39+
val++;
40+
cout<<a[row][col]<<" ";
41+
42+
}
43+
cout<<endl;
44+
}
45+
46+
cout<<"After rotating"<<endl;
47+
rotate(a,n);
48+
49+
for(int row=0;row<m;row++){
50+
for(col=0;col<n;col++){
51+
cout<<a[row][col]<<" ";
52+
53+
}
54+
cout<<endl;
55+
}
56+
57+
58+
59+
60+
61+
62+
63+
return 0;
64+
}
65+
66+
/*
67+
Output
68+
Enter row and column
69+
4
70+
4
71+
1 2 3 4
72+
5 6 7 8
73+
9 10 11 12
74+
13 14 15 16
75+
After rotating
76+
4 8 12 16
77+
2 6 10 14
78+
3 7 11 15
79+
1 5 9 13
80+
*/
81+
82+

0 commit comments

Comments
 (0)