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

[LeetCode] Rotate Image

时间:2015-05-23 00:05:24      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:c++   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?

解题思路:

技术分享

题目要求原地算法。假设坐标轴如上所示。顺时针旋转90度,相当于先将图片沿着x=n/2翻转,然后再将图片沿着斜对角线y=x翻转。代码如下:

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int len = matrix.size();
        //先将矩阵左右翻转
        for(int i = 0; i<len; i++){
            reverse(matrix[i]);
        }
        //再将矩阵沿着x=y翻转
        for(int i=0; i<len; i++){
            for(int j=0; j<len - i; j++){
                int temp = matrix[i][j];
                matrix[i][j]=matrix[len-j-1][len-i-1];
                matrix[len-j-1][len-i-1]=temp;
            }
        }
    }
    
    void reverse(vector<int>& v){
        int len = v.size();
        int i=0, j=len-1;
        while(i<j){
            swap(v, i, j);
            i++;
            j--;
        }
    }
    
    void swap(vector<int>& v, int i, int j){
        int temp = v[i];
        v[i] = v[j];
        v[j] = temp;
    }
};


[LeetCode] Rotate Image

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45922577

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