如何在不使用存储阵列的情况下将2D阵列旋转90度? [英] How do you rotate a 2D array 90 degrees without using a storage array?

查看:94
本文介绍了如何在不使用存储阵列的情况下将2D阵列旋转90度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已指示我不要使用存储阵列来完成此任务.基本上,我们必须创建一个函数,将2d数组的内容旋转90度.

I was instructed not to use a storage array to complete this task. Basically, we have to create a function that rotates the contents of a 2d array 90 degrees.

所以,如果我从这个数组开始:

So if I start off with this array:

int[][] array = {{1,2,3}, {4,5,6}, {7,8,9}};

该函数应返回如下数组:

The function should return an array like this:

{{7,4,1}, {8,5,2}, {9,6,3}}

同样,我们不允许在函数中使用创建的数组进行存储.甚至没有存储阵列也可以完成此操作吗?

Again we are not allowed to use a created array within the function for storage. Is it even possible to accomplish this without a storage array?

推荐答案

我们可以直接打印旋转矩阵,而无需保存结果,如下所示:首先,我们先对列进行遍历,然后对行进行遍历,然后打印点.由于我们事先不知道行的长度,即列数,因此我们迭代到

We can directly print a rotated matrix without saving a result as follows: first we iterate over the columns and then the rows, and print the points. Since we don't know beforehand the length of the row, i.e the number of columns, we iterate up to the Integer.MAX_VALUE and check at each step whether the columns are still present or not.

其余算法与创建转置2d数组时相同.点 [i] [j] 的索引变为 [j] [i] ,但其中一侧的索引等于 the边的长度减去边的当前索引,再减去1 .索引从0开始.

The rest of the algorithm is the same as when creating a transposed 2d array. The indices of points [i][j] become [j][i], but the indices of one of the sides becomes equal to the length of the side, minus the current index of the side, minus 1. Indexes start at 0.

int[][] array = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}};

for (int col = 0; col < Integer.MAX_VALUE; col++) {
    boolean max = true;
    for (int row = 0; row < array.length; row++) {
        if (col < array[row].length) {
    //      System.out.printf("%2d ", // transposed matrix
    //              array[row][col]);
    //      System.out.printf("%2d ", // rotated 90º clockwise ⟳
    //              array[array.length - row - 1][col]);
            System.out.printf("%2d ", // rotated 90º counterclockwise ⟲
                    array[row][array[row].length - col - 1]);
            max = false;
        }
    }
    System.out.println();
    if (max) break;
}

输出(逆时针旋转90º⟲):

Output (rotated 90º counterclockwise ⟲):

 4  8 12 
 3  7 11 
 2  6 10 
 1  5  9 


另请参阅:
首先按列填充锯齿状的二维数组
矩阵的转置

这篇关于如何在不使用存储阵列的情况下将2D阵列旋转90度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆