思想:
同样也是把整个矩阵看成是一圈一圈的进行打印就可以了,打印完一圈之后令左上角坐标向右下角移动,右下角坐标向左上角移动,直到右下角坐标小于左上角坐标为止;
具体的转换策略见图:
实际的操作中,注意将其中的len以及0等进行适当的替换,因为这个只是模拟了遍历最外圈的情形,如果遍历里面圈的话,开始一定不是0啦,而是里圈的最左上角坐标:
代码:
import java.util.Scanner;
public class RotateMatrix {
public static int count = 1;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] mat = new int[n][n];
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
mat[i][j] = in.nextInt();
}
}
rotateMatrix(mat, n);
print(mat, n);
}
public static void rotateMatrix(int[][] mat,int n)
{
int startX = 0;
int startY = 0;
int endX = n-1;
int endY = n-1;
while(startX <= endX && startY <= endY)
{
getTempMatrix(mat, startX, startY, endX, endY,count,n);
startX = startX+1;
startY = startY+1;
endX = endX-1;
endY = endY-1;
count++;
}
}
/**
* 旋转一圈的函数
* @param mat
* @param startX
* @param startY
* @param end
* @param endY
* @param count 表示是第几圈
* @return
*/
public static int[][] getTempMatrix(int[][] mat,int startX,int startY,int endX,int endY,int count,int n)
{
int i,j,k;
int len = n-count;//表示最右边的位置,这个位置会随着已经遍历的圈数的变化而变化,具体变化是每遍历一圈,这个值减1
int temp;//用于临时存放下一个将要访问的值
int temp1;//用于存储下一次的下一次将要访问的值
for(i = startX,j = startY,k = 0;i < endX;i++,j++,k++)
{
temp = mat[i][len];
mat[i][len] = mat[startX][j];
temp1 = mat[len][len-k];
mat[len][len-k] = temp;
temp = temp1;
temp1 = mat[len-k][startY];
mat[len-k][startY] = temp;
temp = temp1;
mat[startX][i] = temp;
}
return mat;
}
/**
* 打印矩阵
* @param mat
* @param n
*/
public static void print(int[][] mat,int n)
{
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
}