如何将二维数组逆时针旋转90º?
How to rotate 2D array 90º anticlockwise?
我需要将给定的矩阵逆时针旋转 90º,但我不知道如何开始。
例如:
从这里开始
5 10 8 9
16 30 25 41
7 17 50 12
45 8 22 34
对此:
9 41 12 34
8 25 50 22
10 30 17 8
5 16 7 45
这就像一个矩阵转置。您可以在循环中使用循环,或在流中使用流:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}
};
int[][] arr2 = new int[d][d];
int[][] arr3 = new int[d][d];
int[][] arr4 = new int[d][d];
IntStream.range(0, d).forEach(i ->
IntStream.range(0, d).forEach(j -> {
// matrix transpose
arr2[j][i] = arr1[i][j];
// turn matrix 90º clockwise
arr3[j][d - 1 - i] = arr1[i][j];
// turn matrix 90º counterclockwise
arr4[d - 1 - j][i] = arr1[i][j];
}));
Arrays.stream(arr4).map(Arrays::toString).forEach(System.out::println);
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
原始矩阵中的每个单元格[i][j]
成为旋转矩阵中的一个单元格[4-1-j][i]
:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}};
int[][] arr2 = new int[d][d];
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++)
arr2[d - 1 - j][i] = arr1[i][j];
for (int row = 0; row < d; row++)
System.out.println(Arrays.toString(arr2[row]));
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
另请参阅:
•
• Is there a way to reverse specific arrays in a multidimensional array?
我需要将给定的矩阵逆时针旋转 90º,但我不知道如何开始。
例如:
从这里开始
5 10 8 9
16 30 25 41
7 17 50 12
45 8 22 34
对此:
9 41 12 34
8 25 50 22
10 30 17 8
5 16 7 45
这就像一个矩阵转置。您可以在循环中使用循环,或在流中使用流:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}
};
int[][] arr2 = new int[d][d];
int[][] arr3 = new int[d][d];
int[][] arr4 = new int[d][d];
IntStream.range(0, d).forEach(i ->
IntStream.range(0, d).forEach(j -> {
// matrix transpose
arr2[j][i] = arr1[i][j];
// turn matrix 90º clockwise
arr3[j][d - 1 - i] = arr1[i][j];
// turn matrix 90º counterclockwise
arr4[d - 1 - j][i] = arr1[i][j];
}));
Arrays.stream(arr4).map(Arrays::toString).forEach(System.out::println);
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
原始矩阵中的每个单元格[i][j]
成为旋转矩阵中的一个单元格[4-1-j][i]
:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}};
int[][] arr2 = new int[d][d];
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++)
arr2[d - 1 - j][i] = arr1[i][j];
for (int row = 0; row < d; row++)
System.out.println(Arrays.toString(arr2[row]));
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
另请参阅:
•
• Is there a way to reverse specific arrays in a multidimensional array?