-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07-Rotate_Matrix
49 lines (39 loc) · 1.29 KB
/
07-Rotate_Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
void rotateMatrix(vector<vector<int>> &mat, int n, int m)
{
// Write your code here
//APPROACH -1
// int k=min(m,n);
// for(int i=0;i<k/2;i++){
// int top=i,left=i,bottom=n-1-i,right=m-1-i;
// int x=mat[top][left];
// for(int j=left+1;j<=right;j++){
// swap(mat[top][j],x);
// }
// for(int j=top+1;j<=bottom;j++){
// swap(mat[j][right],x);
// }
// for(int j=right-1;j>=left;j--){
// swap(mat[bottom][j],x);
// }
// for(int j=bottom-1;j>=top;j--){
// swap(mat[j][left],x);
// }
// }
//Approach-2
if(n==1 || m==1) return;
int top = 0, bot = n-1, left = 0, right = m-1;
while(top<bot && left < right){
int temp = mat[left][top];
for(int i = top;i<bot;i++)
mat[i][left] = mat[i+1][left];
for(int i=left;i<right;i++)
mat[bot][i] = mat[bot][i+1];
for(int i=bot;i>top;i--)
mat[i][right] = mat[i-1][right];
for(int i=right;i>left+1;i--)
mat[top][i] = mat[top][i-1];
mat[top][left+1] = temp;
top++, bot--,left++,right--;
}
}