java - 如何在java中将矩阵逆时针旋转90度?
问题描述
我正在尝试解决《Cracking the Coding Interview》一书中的问题。其中一个问题要求我将矩阵顺时针旋转 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]
我的代码中的缺陷/差异在哪里?
解决方案
如果你画出矩阵来可视化,你会看到你的一些索引是关闭的。例如matrix.length-1
,您应该在更新中使用 bottom 而不是使用 ,因为图层正方形的大小会随着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
推荐阅读
- python-3.x - leetcode“唯一电子邮件地址”问题解释
- prometheus - 将多个指标与唯一标签进行比较时,指标不匹配
- inno-setup - 当文件也与通配符文件部分条目匹配时,Inno Setup 在卸载期间未取消注册文件
- python - Django中的crsf问题
- python - 带有枚举和 for 循环的代码在第一个字母上给了我重复的结果
- linux - 每个信号量的线程堆栈是多少
- python - web2py:如何在使用 SQLFORM.smartgrid 删除之前执行指令
- c# - 使用表和局部变量中的数据进行查询(C# 和 MS-Access、oledb)
- vba - 我再次收到混合单元格宽度错误
- android - 如何在 OnSuccessListener 中的 recyclerview 适配器中传递侦听器