Tranpose and rotate matrix by 90degree (both clockwise and anti-clockwise)🚩🚩
Tue Jan 25 2022 07:51:06 GMT+0000 (Coordinated Universal Time)
Saved by
@vaibhav_55
/*
(this question is asked in many companies)
the,given matrix is n*n matrix
-->transpose of matrix
Steps:-
just swap the lower triangle with the upper triangle of matrix
-->clock-wise rotation by 90 degree
Steps:-
1.first find the transpose using above function
2.the just reverse each row
-->anti-clock-wise rotation by 90 degree
Steps:-
1.first find the transpose using above function
2.the just reverse each column
Time Complexity of all is O(n*n);
*/
vector<vector<int>> transpose(vector<vector<int>> matrix, int n)
{
for (int i = 0; i < n; i++)
for (int j = 0; j <= i; j++)
swap(matrix[i][j], matrix[j][i]);
return matrix;
}
vector<vector<int>> rotate_clock_wise(vector<vector<int>> matrix, int n)
{
// getting the transpose of matrix
matrix = transpose(matrix, n);
// reversing each row
for (int i = 0; i < n; i++)
{
ll s = 0, l = n - 1;
while (s <= l)
{
swap(matrix[i][s], matrix[i][l]);
s++;
l--;
}
}
return matrix;
}
vector<vector<int>> rotate_anti_clock_wise(vector<vector<int>> matrix, int n)
{
// getting the transpose of matrix
matrix = transpose(matrix, n);
// reversing each column
for (int j = 0; j < n; j++)
{
ll s = 0, l = n - 1;
while (s <= l)
{
swap(matrix[s][j], matrix[l][j]);
s++;
l--;
}
}
return matrix;
}
content_copyCOPY
Comments