问题
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)));
}
回答1:
Here is a working example:
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.
回答2:
Looks like you just had your indexes reversed.
Instead of:
rotateM[i][j] = m[j][m.length-i-1];
You should have written:
rotateM[j][i] = m[m.length-i-1][j];
回答3:
When you transpose a matrix, every its cell [i][j] becomes [j][i], but when you rotate a matrix 90 degrees, the indices of one of its sides become equal to the length of the side, minus 1, minus the current index of the side. Indices start at 0.
int m = 2;
int n = 3;
int[][] arr1 = {{10, 20, 30}, {40, 50, 60}};
int[][] arr2 = new int[n][m];
int[][] arr3 = new int[n][m];
int[][] arr4 = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// matrix transpose
arr2[j][i] = arr1[i][j];
// turn matrix 90º clockwise ⟳
arr3[j][m - 1 - i] = arr1[i][j];
// turn matrix 90º anticlockwise ⟲
arr4[n - 1 - j][i] = arr1[i][j];
}
}
| original matrix | matrix transpose | turn matrix 90º ⟳ | turn matrix 90º ⟲ |
|---|---|---|---|
[10, 20, 30] |
[10, 40] |
[40, 10] |
[30, 60] |
See also:
• How do I rotate a matrix 90 degrees counterclockwise in java?
• Is there a way to reverse specific arrays in a multidimensional array in java?
回答4:
Don't increment using i = i++. Just write i++.
回答5:
First of all remove that i = i++.
i++ and j++ will suffice, initialize your arrays and you have your logic wrong:
for (int j = 0; j < m[0].Length; j++)
for (int i = 0; i < m.Length; i++)
rotateM[j][i] = m[m.Length - i - 1][j];
That is what you need.
来源:https://stackoverflow.com/questions/2707595/rotate-a-2d-matrix-to-the-right