Last active
June 8, 2018 11:00
-
-
Save svpino/1ad1a5b4d96429cf8571 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(); | |
} | |
} |
I did it in two steps,
First build the Transpose
Then Swap columns
I feel this solution is easier to implement , I dont know. :)
https://gist.github.com/Qassas/1336b9c6d27fcd933d4bea8f76e40827#file-programming-challenge-rotating-a-matrix-90-degrees-in-place-cpp
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was working with matrices the other day and came up with the same solution, and then thought back to the post. I was writing Haskell, where this literally looks like this:
Note that by reversing each of the columns, we get a clockwise rotation and when reversing the columns themselves, we get a counter-clockwise rotation. Obviously, because this is Haskell, there is no in-place transformation, because data is immutable.