4

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)));
}
adam
  • 71
  • 1
  • 2
  • 4

5 Answers5

2

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.

Community
  • 1
  • 1
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
1

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];
kurige
  • 3,749
  • 2
  • 21
  • 24
0

Don't increment using i = i++. Just write i++.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

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.

Community
  • 1
  • 1
Francisco Soto
  • 10,277
  • 2
  • 37
  • 46
0

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]
[40, 50, 60]
[10, 40]
[20, 50]
[30, 60]
[40, 10]
[50, 20]
[60, 30]
[30, 60]
[20, 50]
[10, 40]

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?