0

I asked yesterday for a solution for rotating an 2d array with n*m. I get this link as answer: How do you rotate a two dimensional array?

I tryed my best and I thougt it works fine. And yes it works for an n*n array but if n and m are different I get an IndexOutOfBounds Error and I have no Idea why.

Here is my code:

    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;           
}

Thank you a lot for helping.

Community
  • 1
  • 1
wit4r7
  • 125
  • 1
  • 13
  • well, the question you've linked to has clearly stated the solution is for a _multi-dimensional array_, meaning fixed rows and columns. they **cannot** be _jagged_. – Ousmane D. May 15 '17 at 18:10

1 Answers1

3

Because, when you rotate a 2d array, the rows becomes columns and the columns becomes the row. Rotating in the same matrix is possible only if n==m. If n!=m then you need to declare a new 2d array.