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