[英]How do you rotate a 2D array 90 degrees without using a storage array?
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.
基本上,我们必须创建一个将二维数组的内容旋转 90 度的函数。
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]));
}
}
}
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, ie 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.由于我们事先不知道行的长度,即列数,我们迭代到
Integer.MAX_VALUE
并在每一步检查列是否仍然存在。
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
.点
[i][j]
的索引变为[j][i]
,但其中一个边的索引变为等于边the length of the side, minus the current index of the side, minus 1
。 Indexes start at 0.索引从 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;
}
Output (rotated 90º counterclockwise ⟲):输出(逆时针旋转 90º ⟲):
4 8 12
3 7 11
2 6 10
1 5 9
See also:也可以看看:
• Filling a jagged 2d array first by columns •首先按列填充锯齿状二维数组
• The transpose of a matrix •矩阵的转置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.