如何在不使用存储阵列的情况下将二维阵列旋转 90 度?

我被指示不要使用存储阵列来完成此任务.基本上,我们必须创建一个将二维数组的内容旋转 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?

推荐答案

您可以通过将上半部分与下半部分一一交换来旋转/转置数组:

You can rotate/transpose the array by swapping the upper half with the lower half one by one:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[][] array = new int[][] {
            new int[] { 1, 2, 3},
            new int[] { 4, 5, 6},
            new int[] { 7, 8, 9},
        };

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < row; col++) {
                int t = array[row][col];
                array[row][col] = array[col][row];
                array[col][row] = t;
            }
        }

        for (int row = 0; row < 3; row++) {
            System.out.println(Arrays.toString(array[row]));
        }
    }
}

相关文章