How do you rotate a 2D array 90 degrees without using a storage array?(如何在不使用存储阵列的情况下将二维阵列旋转 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]));
}
}
}
这篇关于如何在不使用存储阵列的情况下将二维阵列旋转 90 度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不使用存储阵列的情况下将二维阵列旋转 90 度?


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01