Rotate Matrix

Last updated: 29th Aug, 2020

        

Problem Statment

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).

Example 1:

If the array is
[
[1, 2],
[3, 4]
]

>> Then the rotated array becomes:
[
[3, 1],
[4, 2]
]

Approach:

As we have to rotate the matrix image by 90. We can change the traversal of the matrix . If we print the column first from downward to upward direction then then the rotated array will be printed .

Time and Space Complexity :
Time - O(n^2)
Space - O(n)

Pseudocode :
for(j=0 to n)
 for(i=n-1 to 0)
  print(a[i][j])

C++ Code
int main()
{
	cout<<"Enter the size of 2D array"<<endl;
	int n;
	cin>>n;
	int a[n][n];
	cout<<"Enter the array elements"<<endl;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			cin>>a[i][j];
		}
		cout<<endl;
	}
	//Rotation by 90
	cout<<"Rotated array"<<endl;
	for(int j=0;j<n;j++)
	{
		for(int i=n-1;i>=0;i--)
		{
			cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}