首页 > 代码库 > Leetcode: Rotate Image

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 down10                 matrix[m-1-layer][m-1-i] = matrix[i][m-1-layer]; // down is substitued by right11                 matrix[i][m-1-layer] = temp; // right is substituted by stored elements12             }13         }14     }15 }