gpt4 book ai didi

java.lang.ArrayIndexOutOfBoundsException : 90 - rotating n*m array

转载 作者:行者123 更新时间:2023-12-01 20:25:03 26 4
gpt4 key购买 nike

我昨天询问了一个用 n*m 旋转二维数组的解决方案。我得到这个链接作为答案:How do you rotate a two dimensional array?

我尽力了,我认为效果很好。是的,它适用于 n*n 数组,但如果 n 和 m 不同,我会收到 IndexOutOfBounds 错误,但我不知道为什么。

这是我的代码:

    public void rot90DegRight(){
//get Matrix
this.Matrix = getMatrix();

int rows = Matrix.length;
int cols = Matrix[0].length;

// create a mirror of current matrix
RGBColor[][] mirror = getMatrix();
// create a new matrix

for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
Matrix[j][rows - i - 1] = mirror[i][j];
}
}

// replace cols count with rows count
int tmp = rows;
rows = cols;
cols = tmp;
}

非常感谢您的帮助。

最佳答案

因为,当旋转二维数组时,行变成列,列变成行。仅当 n==m 时才可以在同一矩阵中进行旋转。如果 n!=m 那么你需要声明一个新的二维数组。

关于java.lang.ArrayIndexOutOfBoundsException : 90 - rotating n*m array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986054/

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