简体   繁体   English

如何将3x3 2d阵列顺时针旋转n次

[英]How to rotate 3x3 2d array clockwise by n times

These are my loop statements. 这些是我的循环语句。 The first loop displays the non-rotated block while the second loop rotates and displays the 2d array by n(user input) times. 第一个循环显示未旋转的块,而第二个循环旋转并以n(用户输入)次显示2d数组。 My problem is that the 2d array will rotate once but will not rotate the third and following times around. 我的问题是2d阵列将旋转一次,但不会旋转第三次及之后的时间。 I want my 2d array to rotate 90 degrees clockwise every time it is displayed. 我希望我的2d数组每次显示时都顺时针旋转90度。

        rot = x.nextInt(); //user input for n rotations
        //initial block
        System.out.println("1");
        for(i=0; i<block.length; i++)
            {
                for(j=0; j<block[i].length; j++)
                    System.out.print(block[i][j]+"\t");
                System.out.println();
            }
        //rotated block
        for(cnt=2; cnt<=rot; cnt++)
        {
            System.out.println(cnt);
            for(i=0; i<block.length; i++){
                for(j=block.length-1; j>=0; j--){
                    newBlock[i][j] = block[j][i];
                    System.out.print(newBlock[i][j]+"\t");
                }
                System.out.println();
            }
        }

Your current rotation code is wrong AFAIK because you are just transposing the array. 您当前的旋转代码是错误的AFAIK,因为您只是在转置数组。 Doing this twice is effectively a no-op because it leaves the matrix in its original state. 两次执行此操作实际上是一个空操作,因为它使矩阵保持原始状态。 It should be intuitive to you that rotating a matrix by 90 degrees twice (ie rotating once by 180 degrees) should not, in general, leave the matrix unchanged. 您应该直观地知道,将矩阵旋转两次90度(即旋转180度一次)通常不应使矩阵保持不变。 Try this rotation code instead: 请尝试以下旋转代码:

int dim = block.length;

for (int i=0; i <= (dim - 1)/2; i++) {
    for (int j=i; j < dim - i - 1; j++) {
        int p1 = block[i][j];
        int p2 = block[j][dim-i-1];
        int p3 = block[dim-i-1][dim-j-1];
        int p4 = block[dim-j-1][i];

        block[j][dim-i-1] = p1;
        block[dim-i-1][dim-j-1] = p2;
        block[dim-j-1][i] = p3;
        block[i][j] = p4;
    }
}

I adapted this in-place matrix rotation code from this Quora article . 我从Quora文章中改编了此原位矩阵旋转代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM