有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。
给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵。不要新开辟空间。
n*n的矩阵: 先确定循环的次数。 四个角顺时针分别是a b c d,然后循环交换位置。然后a 右移,b 下移,c 左移,d上移,开始下一轮循环。直到a 遇到 c 循环结束。
public static void rotateMatrix(int[][] mat, int n) {
int a = 0;
int b = 0;
int c = mat.length-1;
int d = mat[0].length - 1;
while (a < c) {
rotateMatrix(mat,a++,b++,c--,d--);
}
}
public static void rotateMatrix(int[][] mat, int a,int b,int c,int d){
int count=c-a;
for (int i = 0; i <count ; i++) {
int aa=mat[a][b+i];
int bb=mat[a+i][d];
int cc=mat[c][d-i];
int dd=mat[c-i][a];
int temp=aa;
mat[a][b+i]=dd;
mat[a+i][d]=temp;
mat[c][d-i]=bb;
mat[c-i][a]=cc;
for(int x=0;x<mat.length;x++){
for(int y=0;y<mat[0].length;y++){
System.out.print(mat[x][y]);
}
System.out.println();
}
}
}