1
public static int[][] rotate(int[][] array){
    int height = array.length;
    int width = array[0].length;
    int[][] rotatedArray = array;

    for(int col = 0; col < width; col++){
        for(int row = 0; row < height; row++){
            rotatedArray[row][col] = array[col][row];
        }
    }
    return rotatedArray;
}

This is my code as method to rotate image 90 degree counter-wise, but it doesn't work. I have no idea how to arrange new rows and columns and rotate it properly, how can I fix it? Thanks!

yolam
  • 59
  • 1
  • 6

2 Answers2

1

Try rotatedArray[row][col] = array[col][height - row - 1];.

Also, you need to define rotatedarray as a new array. Right now, you're assigning it array, which means they are both referencing the same data.

Here's how you can do it:

public static int[][] rotate(int[][] array) {
    int height = array[0].length;
    int width = array.length;
    int[][] rotatedArray = new int[height][];

    for(int row = 0; row < height; row++) {
        rotatedArray[row] = new int[width];
        for(int col = 0; col < width; col++) {
            rotatedArray[row][col] = array[col][height - row - 1];
        }
    }
    return rotatedArray;
}

Note that the height of the original array becomes the width of the new array and vice versa.

John Sensebe
  • 1,386
  • 8
  • 11
0

By transposing the row & column indices with rotatedArray[row][col] = array[col][row], you are mirroring the image along the diagonal, instead of rotating it. Think about it - any entry where both indices are matching such as array[0][0] or array[1][1] is unchanged. That's not what you want!

I would recommend drawing a picture to see what pattern you see. You can start with very small examples, 2-by-2 or 3-by-3.