Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created December 29, 2013 02:47
Show Gist options
  • Save wayetan/8166907 to your computer and use it in GitHub Desktop.
Save wayetan/8166907 to your computer and use it in GitHub Desktop.
Rotate Image
/**
* You are given an n x n 2D matrix representing an image.
* Rotate the image by 90 degrees (clockwise).
* Follow up:
* Could you do this in-place?
*/
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n / 2; i++){
int first = i;
int last = n - i - 1;
for(int j = first; j < last; j++){
int offset = j - first;
int top = matrix[first][j];
matrix[first][j] = matrix[last - offset][first];
matrix[last - offset][first] = matrix[last][last - offset];
matrix[last][last - offset] = matrix[j][last];
matrix[j][last] = top;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment