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 度?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
