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

LeetCode Rotate Image

时间:2015-01-21 23:52:48      阅读:133      评论: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?

 

可以找规律 得出映射关系,(i,j)===>(j,n-1-j)

由于要in-place,不能直接新建矩阵,所以从外圈开始,一个个置换。

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         int n = matrix[0].length -1;
 4         for(int i = 0;i <= n - i;i++){
 5             for(int j = i;j <= n - i - 1;j++)
 6             {
 7                 int tmp = matrix[j][n-i];
 8                 matrix[j][n-i] = matrix[i][j];
 9                 matrix[i][j] = matrix[n-j][i];
10                 matrix[n-j][i] = matrix[n-i][n-j];
11                 matrix[n-i][n-j] = tmp;
12             }
13         }
14     }
15 }

 

LeetCode Rotate Image

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4240358.html

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