LeetCode --- Rotate Image
2015-03-03 14:57:48         来源：makuiyu的专栏

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Could you do this in-place?

# 1. 逐个旋转

`````` 1 class Solution
2 {
3 public:
4     void rotate(vector > &matrix)
5     {
6         int n = matrix.size();
7         for(int i = 0; i < n / 2; ++ i)
8             for(int j = i; j < n - i - 1; ++ j)
9             {
10                 int temp = matrix[i][j];
11                 matrix[i][j] = matrix[n - j - 1][i];
12                 matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
13                 matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
14                 matrix[j][n - i - 1] = temp;
15             }
16     }
17 };``````

`````` 1 class Solution
2 {
3 public:
4     void rotate(vector > &matrix)
5     {
6         int n = matrix.size();
7         for(int i = 0; i < n / 2; ++ i)
8             for(int j = i; j < n - i - 1; ++ j)
9             {
10                 swap(matrix[i][j], matrix[n - j - 1][i]);
11                 swap(matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1]);
12                 swap(matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1]);
13             }
14     }
15 };``````

# 2. 先翻转，在对换

``````1 2 3     7 8 9     7 4 1
4 5 6  => 4 5 6  => 8 5 2
7 8 9     1 2 3     9 6 3
``````

`````` 1 class Solution
2 {
3 public:
4     void rotate(vector > &matrix)
5     {
6         reverse(matrix.begin(), matrix.end());
7         for(int i = 0; i < matrix.size(); ++ i)
8             for(int j = 0; j < i; ++ j )
9                 swap(matrix[i][j], matrix[j][i]);
10     }
11 };``````