/** * @author lautturi.com * Java example: rotate a matrix 90 degrees clockwise in java */ import java.util.*; public class Lautturi { public static void main(String[] args) { int matrix[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8, 13 }, { 9, 10, 11, 12 } }; // print the matrix/2d-array in java for (int[] subarray : matrix) { for (int element : subarray) { System.out.printf("%5d", element); } System.out.println(); } // rotate the matrix/2d-array 90 degrees in java int maxrows = matrix.length; int maxcols = 0; for (int row = 0; row < maxrows; row++) { maxcols = matrix[row].length > maxcols ? matrix[row].length : maxcols; } int newMatrix[][] = new int[maxcols][maxrows]; for (int col = 0; col < maxcols; col++) { for (int row = 0; row < maxrows; row++) { int oriCols = matrix[row].length; if (col < oriCols) newMatrix[col][row] = matrix[maxrows - 1 - row][col]; // else // newMatrix[col][row] = -1; } } System.out.println("-------------"); // print the matrix/2d-array in java for (int[] subarray : newMatrix) { for (int element : subarray) { System.out.printf("%5d", element); } System.out.println(); } } }
output:
, 1 2 3 4 5 6 7 8 13 9 10 11 12 ------------- 9 5 1 10 6 2 11 7 3 12 8 4 0 13 0