I want the 2d matrix to rotate to the right, it compiles fine, but when I try to run it means that the array index is out of range. For example, I want {{10,20,30}, {40,50,60}} to rotate in {{40,10}, {50,20}, {60,30}}
import java.util.*; public class Rotate{ 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))); }
}
source share