Rotate a 2d matrix to the right(向右旋转二维矩阵)
问题描述
我想要一个 2d 矩阵向右旋转,它编译得很好,但是当我尝试运行时,它说 数组索引超出范围异常.例如,我希望 {{10,20,30},{40,50,60}}
旋转成 {{40,10},{50,20},{60,30}}
:
I want a 2d matrix to rotate to the right, it compiles fine but when I try to the run it says that the array index is out of bounds exception. For example, I want {{10,20,30},{40,50,60}}
to rotate into {{40,10},{50,20},{60,30}}
:
public static int[][] rotate(int[][] m) {
int[][] rotateM = new int[m[0].length][m.length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
rotateM[i][j] = m[j][m.length - i - 1];
}
}
return rotateM;
}
public static void main(String[] args) {
int[][] m = {
{10, 20, 30},
{40, 50, 60}};
System.out.println(Arrays.toString(rotate(m)));
}
推荐答案
这是一个工作示例:
private int[][] rotateMatrix(int[][] matrix) {
int backupH = h;
int backupW = w;
w = backupH;
h = backupW;
int[][] ret = new int[h][w];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
ret[i][j] = matrix[w - j - 1][i];
}
}
return ret;
}
我使用此代码在俄罗斯方块中旋转我的积木.此代码顺时针旋转矩阵.
I used this code to rotate my bricks in Tetris. This code rotates the matrix clockwise.
这篇关于向右旋转二维矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向右旋转二维矩阵


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01