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

【Rotate Image】cpp

时间:2015-04-26 18:03:09      阅读:99      评论: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?

代码

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
            const unsigned int len = matrix.size();
            if ( len < 2 ) return;
            for ( int row = 0; row < len; ++row)
            {
                for (int col = 0; col < len-1-row; ++col)
                {
                    std::swap(matrix[row][col], matrix[len-1-col][len-1-row]);
                }
            }
            for ( int row = 0; row < len/2; ++row)
            {
                for ( int col = 0; col < len; ++col)
                {
                    std::swap(matrix[row][col], matrix[len-1-row][col]);
                }
            }
    }
};

Tips:

1. 算法:先沿着副对角线(右上到左下)swap元素;再沿着水平中轴线swap元素

2. 注意循环遍历时的结束条件,不要做无谓的遍历

【Rotate Image】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4457942.html

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