转自:http://www.cnblogs.com/graph/archive/2013/07/31/3229056.html
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?
|
The rotation can be performed in layers, where you perform a cyclic swap on the edges on
each layer In the frst for loop, we rotate the frst layer (outermost edges) We rotate the
edges by doing a four-way swap frst on the corners, then on the element clockwise from the
edges, then on the element three steps away
Once the exterior elements are rotated, we then rotate the interior region’s edge
class Solution { public: void rotate(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = matrix.size(); if(n < 2) return ; for(int lay = 0 ; lay < n/2; lay ++){ int first = lay ; int last = n - 1 - lay; for(int i = first; i< last; i++){ int offset = i - first; //store the top int top = matrix[first][i] ; //left to top matrix[first][i] = matrix[last - offset][first]; //bottom to left matrix[last - offset][first] = matrix[last][last- offset]; //right to bottom matrix[last][last - offset] = matrix[i][last]; //top to right matrix[i][last] = top; } } } };
--------------------------------------------------------------------天道酬勤!