Sunday, May 5, 2013

Rotate a 2-D matrix by 90° counter-clockwise


#include<iostream>
using namespace std;
int main()
{
int n,A[100][100];
cout<<"Enter the dimension of the square matrix:"<<endl;
cin>>n;
cout<<"Enter the elements:"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>A[i][j];
}
}
for(int i=0;i<n/2;i++)
{
for(int j=i;j<n-1-i;j++)
{
int t=A[i][j];
A[i][j]=A[j][n-1-i];
A[j][n-1-i]=A[n-1-i][n-1-j];
A[n-1-i][n-1-j]=A[n-1-j][i];
A[n-1-j][i]=t;
}
}
cout<<"The counter-clockwise rotated matrix is:"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<A[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Output:
Enter the dimension of the square matrix: 4
Enter the elements:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
The counter-clockwise rotated matrix is:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4