Leetcode: 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?

抠细节的题,题目思想如下:to implement the rotation in layers, if size is n, so there will be (int)(n / 2) layers that should be rotated. 

需要注意的是:在下面这段code里面,需要注意的是:每一层layer中 i 的取值范围是 0<= i < m - layer - 1,注意上限是m-layer-1, 不是m-layer,如果是m-layer,就会多移。。造成意想不到的结果

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         int m = matrix.length;
 4         if (m == 0) return; 
 5         for (int layer = 0; layer < m / 2; layer++) {
 6             for (int i = layer; i < m - layer - 1; i++) {
 7                 int temp = matrix[layer][i]; //store up elements
 8                 matrix[layer][i] = matrix[m-1-i][layer]; // up is substituted by left
 9                 matrix[m-1-i][layer] = matrix[m-1-layer][m-1-i]; // left is substituted by down
10                 matrix[m-1-layer][m-1-i] = matrix[i][m-1-layer]; // down is substitued by right
11                 matrix[i][m-1-layer] = temp; // right is substituted by stored elements
12             }
13         }
14     }
15 }

Another solution from Leetcode discussion

 1 /*
 2  * clockwise rotate
 3  * first reverse up to down, then swap the symmetry 
 4  * 1 2 3     7 8 9     7 4 1
 5  * 4 5 6  => 4 5 6  => 8 5 2
 6  * 7 8 9     1 2 3     9 6 3
 7 */
 8 void rotate(vector<vector<int> > &matrix) {
 9     reverse(matrix.begin(), matrix.end());
10     for (int i = 0; i < matrix.size(); ++i) {
11         for (int j = i + 1; j < matrix[i].size(); ++j)
12             swap(matrix[i][j], matrix[j][i]);
13     }
14 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/3794338.html