首页 > 其他 > 详细

Leetcode: Rotate Image

时间:2014-06-28 22:08:07      阅读:365      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!