Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created June 21, 2014 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/2722328bce613265cf19 to your computer and use it in GitHub Desktop.
Save chrislukkk/2722328bce613265cf19 to your computer and use it in GitHub Desktop.
CareerCup_1.6 - Matrix Rotation
package Chapter1;
import java.util.Random;
public class MartrixRotation {
public static void rotateClockWise(int[][] matrix) {
if (matrix == null || matrix.length <= 1)
return;
int N = matrix.length; // NxN matrix
for (int i = 0; i < N / 2; i++) {
for (int j = i; j < N - 1 - i; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[N - 1 - j][i];
matrix[N - 1 - j][i] = matrix[N - 1 - i][N - 1 - j];
matrix[N - 1 - i][N - 1 - j] = matrix[j][N - 1 - i];
matrix[j][N - 1 - i] = tmp;
}
}
}
public static void print(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void randomInit(int[][] matrix) {
Random r = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = Math.abs(r.nextInt() % 1001);
}
}
}
public static void main(String[] args) {
int[][] mat = new int[5][5];
randomInit(mat);
print(mat);
System.out.println();
rotateClockWise(mat);
print(mat);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment