Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 15:22
Show Gist options
  • Select an option

  • Save pdu/4971864 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971864 to your computer and use it in GitHub Desktop.
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? http://leetcode.com/onlinejudge#question_48
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int n = matrix.size();
for (int leftx = 0; leftx < n / 2; leftx++) {
int len = n - leftx * 2;
int rightx = leftx + len - 1;
for (int i = 0; i < len - 1; ++i) {
int tmp = matrix[leftx][leftx + i];
matrix[leftx][leftx + i] = matrix[rightx - i][leftx];
matrix[rightx - i][leftx] = matrix[rightx][rightx - i];
matrix[rightx][rightx - i] = matrix[leftx + i][rightx];
matrix[leftx + i][rightx] = tmp;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment