Thursday, February 11, 2016

LeetCode Q48: 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?

Rotate layer by layer. In each layer move 4 elements in the same time.

class Solution {
public:
void rotate(vector<vector<int> >& matrix) {
int layers=ceil(matrix.size()/2);
int N=matrix.size();
int n=N;
for(int i=layers; i>=1; i--){
int r=layers-i;
for(int j=r; j<r+n-1; j++){
int c=j;
int u=matrix[r][c];
int rt=matrix[c][N-layers+i-1];
int d=matrix[N-layers+i-1][N-c-1];
int l=matrix[N-c-1][layers-i];
matrix[c][N-layers+i-1]=u;
matrix[N-layers+i-1][N-c-1]=rt;
matrix[N-c-1][layers-i]=d;
matrix[r][c]=l;
}
n=n-2; // get to next layers inside
}
}
};

No comments:

Post a Comment