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?
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
private:
void Mirror(vector<vector<int> >& matrix)
{
const int N = matrix.size();
const int Half = N / 2;
for (int IndexOfRows = 0; IndexOfRows < N; IndexOfRows++)
{
for (int IndexOfCols = 0; IndexOfCols < Half; IndexOfCols++)
{
int Tmp = matrix[IndexOfRows][IndexOfCols];
matrix[IndexOfRows][IndexOfCols] = matrix[IndexOfRows][N - 1 - IndexOfCols];
matrix[IndexOfRows][N - 1 - IndexOfCols] = Tmp;
}
}
}
void RotateFour(vector<vector<int> >& matrix)
{
const int N = matrix.size();
for (int IndexOfRows = 0; IndexOfRows < N - 1; IndexOfRows++)
{
for (int IndexOfCols = 0; IndexOfCols < N - 1 - IndexOfRows; IndexOfCols++)
{
int Tmp = matrix[IndexOfRows][IndexOfCols];
matrix[IndexOfRows][IndexOfCols] = matrix[N - 1 - IndexOfCols][N - 1 - IndexOfRows];
matrix[N - 1 - IndexOfCols][N - 1 - IndexOfRows] = Tmp;
}
}
}
public:
void rotate(vector<vector<int> > &matrix)
{
// 水平对称
Mirror(matrix);
// 45度对称
RotateFour(matrix);
}
};

原文:http://blog.csdn.net/sheng_ai/article/details/44895579