码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Rotate Image

时间:2014-06-28 22:11:37      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   c   leetcode   

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 }

 

Leetcode: Rotate Image,布布扣,bubuko.com

Leetcode: Rotate Image

标签:style   blog   color   for   c   leetcode   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3794338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!