-
-
Save tusharbihani/495dacf091c4a8a98a3917640d8ed431 to your computer and use it in GitHub Desktop.
Programming challenge: rotating a matrix 90 degrees in place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Programming challenge: rotating a matrix 90 degrees in place | |
// Original post: https://blog.svpino.com/2015/05/10/programming-challenge-rotating-a-matrix-90-degrees-in-place | |
public class RotatingMatrix90DegreesInPlace { | |
private static int[][] matrix = { | |
{ 1, 2, 3, 4 }, | |
{ 5, 6, 7, 8 }, | |
{ 9, 10, 11, 12 }, | |
{ 13, 14, 15, 16 } | |
}; | |
private final static int N = 4; | |
private static void print() { | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < N; j++) { | |
System.out.print("\t" + matrix[i][j]); | |
} | |
System.out.println(); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
print(); | |
for (int ring = 0; ring < N / 2; ring++) { | |
int farthest = N - ring - 1; | |
for (int i = ring; i < farthest; i++) { | |
int temp = matrix[ring][i]; | |
matrix[ring][i] = matrix[farthest - i + ring][ring]; | |
matrix[farthest - i + ring][ring] = | |
matrix[farthest][farthest - i + ring]; | |
matrix[farthest][farthest - i + ring] = | |
matrix[i][farthest]; | |
matrix[i][farthest] = temp; | |
} | |
} | |
print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment