-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotateMatrix.java
61 lines (52 loc) · 1.04 KB
/
RotateMatrix.java
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
50
51
52
53
54
55
56
57
58
59
60
61
public class RotateMatrix {
static int R=3,C=3;
public static void main(String[] args) {
int a[][] = {{1 ,2, 3},
{4, 5 ,6},
{7 ,8, 9}};
rotatematrix(R, C, a);
}
private static void rotatematrix(int m, int n, int[][] mat) {
int row=0,col=0;
int prev=0,curr=0;
while(row<m && col<n){
if(row+1==m && col+1==n)
break;
prev=mat[row+1][col];
for(int i=col;i<n;i++){
curr=mat[row][i];
mat[row][i]=prev;
prev=curr;
}
row++;
for(int i=row;i<m;i++){
curr=mat[i][n-1];
mat[i][n-1]=prev;
prev=curr;
}
n--;
if(row<m){
for(int i=n-1;i>=col;i--){
curr=mat[m-1][i];
mat[m-1][i]=prev;
prev=curr;
}
}
m--;
if(col<n){
for(int i=m-1;i>=row;i--){
curr=mat[i][col];
mat[i][col]=prev;
prev=curr;
}
}
col++;
}
for(int i=0;i<R;i++){
for(int j=0;j<C;j++){
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
}