Java “矩阵”;“层”;轮换

Java “矩阵”;“层”;轮换,java,matrix,rotation,Java,Matrix,Rotation,考虑一个m*n阶矩阵 它有l层 我需要逆时针旋转每一层 这是我想出的密码 int a1=0; // a1,a2,a3,a4 are counters which start at beginning and the end of each row and column and are then moved to the next layers int a2=m-1; int a3=n-1; int a4=0;

考虑一个m*n阶矩阵

它有l层

我需要逆时针旋转每一层



这是我想出的密码

        int a1=0; // a1,a2,a3,a4 are counters which start at beginning and the end of each row and column and are then moved to the next layers
        int a2=m-1;
        int a3=n-1;
        int a4=0;
        for(int j=0;j<l;j++) // l is the layers of the matrix
        {
            c=rotate(a,a1,a2,a3,a4);
            a1++;
            a2--;
            a3--;
            a4++; 
        }
int a1=0;//a1、a2、a3、a4是计数器,从每行和每列的开头和结尾开始,然后移动到下一层
int a2=m-1;
int a3=n-1;
int a4=0;

对于(int j=0;j这里是我如何解决问题的一个非常高层次的概述。可能不是最有效的解决方案,所以请告诉我您是否可以改进

  • 我们应该使用模来“旋转”矩阵,所以首先形成一个环数组,从最外面的环开始,到最里面的环结束

    在这里,我定义了环上的几个关键点:
    右上
    右下
    左下
    ,其中每个点对应于环上的索引。使用这些点来确定点在矩阵上的映射位置

  • 现在,使用
    旋转%ring\u length
    作为指针,从环数组重构矩阵,就像使用常规数组旋转一样


  • 你可以从给变量起一个有意义的名字开始。令人惊讶的是,当代码对人来说是可读的时候,复杂的问题变得如此容易?我看不出有任何有意义的名字editing@SharonBenAsher你还想要什么?
    public static int[][] rotate(int a[][],int a1,int a2,int a3,int a4){
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(j==a1 && i<a2)   
                    c[i+1][j]=a[i][j]; 
                if(i==a2&& j<a3) 
                    c[i][j+1]=a[i][j];
                if(j==a3 && i>a4)   
                    c[i-1][j]=a[i][j];
                if(i==a4 && j>a1)     
                    c[i][j-1]=a[i][j];}}
        return c;}
    
    for(int i=0;i<r;i++)
        {
            int a1=0;
            int a2=m-1;
            int a3=n-1;
            int a4=0;
            for(int j=0;j<l;j++)
            {
                c=rotate(c,a1,a2,a3,a4); // c was initialized to a 
                a1++;
                a2--;
                a3--;
                a4++; 
            }  
        }
    
    public static int[][] rotate(int a[][],int a1,int a2,int a3,int a4){
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(j==a1 && i+r<a2)   //a1,a2
                    c[i+r][j]=a[i][j]; 
                if(i==a2 && j+r<a3) //a2,a3
                    c[i][j+r]=a[i][j];
                if(j==a3 && i-r>a4)   //a3,a4
                    c[i-r][j]=a[i][j];
                if(i==a4 && j-r>a1)     //a4,a1
                    c[i][j-r]=a[i][j];}}
        return c;}