Skip to content

Instantly share code, notes, and snippets.

@svpino
Last active June 8, 2018 11:00
Show Gist options
  • Save svpino/1ad1a5b4d96429cf8571 to your computer and use it in GitHub Desktop.
Save svpino/1ad1a5b4d96429cf8571 to your computer and use it in GitHub Desktop.
Programming challenge: rotating a matrix 90 degrees in place
// 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();
}
}
@sulami
Copy link

sulami commented Jul 25, 2015

You can simply do two pass process to the matrix: first transpose, and then flip horizontally, that means the subscript changes as (i, j)->(j, i)->(j, n-1-i).

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:

import Data.List (transpose)

cw :: [[a]] -> [[a]]
cw = (map reverse) . transpose

ccw :: [[a]] -> [[a]]
ccw = reverse . transpose

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.

@Qassas
Copy link

Qassas commented Aug 23, 2016

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