gpt4 book ai didi

java - java中如何将矩阵逆时针旋转90度?

转载 作者:行者123 更新时间:2023-12-02 01:27:20 24 4
gpt4 key购买 nike

我正在尝试复习《破解编码面试》书中的问题。其中一个问题要求我将矩阵顺时针旋转 90 度。现在,在试图巩固我对矩阵旋转的理解的同时,我尝试着手解决一个新问题:尝试将矩阵逆时针旋转 90 度(另一个方向)。

我尝试遍历方阵的各层,即外层,一直迭代到内层,并逐一旋转“正方形”每一侧的所有索引。这基本上就是 Gayle Laakman McDowell 的解决方案所实现的,但方向相反。

public static void rotateMatrix(int[][] matrix) {
if (matrix.length == 0) {
return;
}
for (int i = 0; i < matrix.length / 2; i++) {
int top = i;
int bottom = matrix.length - 1 - i;
for (int j = top; j < bottom; j++) {
int temp = matrix[top][j];
matrix[top][j] = matrix[j][matrix.length - 1 - j];
matrix[j][matrix.length - 1 - j] = matrix[bottom][j];
matrix[bottom][j] = matrix[j][matrix.length - 1 - bottom];
matrix[j][matrix.length - 1 - bottom] = temp;
}
}
}

我期望样本矩阵的结果

[1,2,3]
[4,5,6]
[7,8,9]

成为

[3,6,9]
[2,5,8]
[1,4,7]

但是我的代码导致了

[1,5,7]
[2,8,6]
[3,4,9]

我的代码中的缺陷/差异在哪里?

最佳答案

如果您绘制矩阵进行可视化,您会发现某些索引已关闭。例如,您应该在更新中使用 Bottom,而不是使用 matrix.length-1,因为图层正方形的大小会随着 i 的增加而减小。另一个错误是,在第二次更新中,您应该:

matrix[j][bottom] = matrix[bottom][bottom - (j - top)];

而不是:

matrix[j][bottom] = matrix[bottom][j];

这是因为在图层的底行中,索引从最后一列开始向后移动到第一列。 j - top 表示您位于图层顶行的距离。绘制出矩阵后,我发现正确的更新如下:

public static void main(String[] args) {
int n = 5;
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = i * n + j + 1;
}
}
rotateMatrix(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.printf("%3d", a[i][j]);
}
System.out.println();
}
}
public static void rotateMatrix(int[][] matrix) {
if (matrix.length == 0) {
return;
}
for (int i = 0; i < matrix.length / 2; i++) {
int top = i;
int bottom = matrix.length - 1 - i;
for (int j = top; j < bottom; j++) {
int temp = matrix[top][j];
matrix[top][j] = matrix[j][bottom];
matrix[j][bottom] = matrix[bottom][bottom - (j - top)];
matrix[bottom][bottom - (j - top)] = matrix[bottom - (j - top)][top];
matrix[bottom - (j - top)][top] = temp;
}
}
}

输出:

5 10 15 20 25
4 9 14 19 24
3 8 13 18 23
2 7 12 17 22
1 6 11 16 21

关于java - java中如何将矩阵逆时针旋转90度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56719451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com