Rotate by 90 degree
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.
Example 1:
Input:
N = 3
matrix[][] = {{1, 2, 3},
{4, 5, 6}
{7, 8, 9}}
Output:
Rotated Matrix:
3 6 9
2 5 8
1 4 7
Example 2:
Input:
N = 2
matrix[][] = {{1, 2},
{3, 4}}
Output:
Rotated Matrix:
2 4
1 3
method 1:
c++ implementation:
void rotateby90(int n, int m[][n])
{
int a[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=m[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
m[n-1-j][i]=a[i][j];
}
}
}
Time Complexity: O(n*n)
space Complexity: O(n*n)
method 2:
first transpose the matrix than reverse the rows of the matrix
void rotateby90(int n, int m[][n])
{
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
swap(m[i][j], m[j][i]); //transpose the matrix
for (int i = 0; i < n/2; i++)
for (int j = 0; j < n; j++)
swap(m[i][j],m[n-i-1][j]); //reverse the rows
}
Time Complexity: O(n*n)
space Complexity: O(1)
No comments