Leetcode Rotate Image

Leetcode Rotate Image 解决方法,本方法通过把一个矩阵分割成不同的环,然后对很一个环进行旋转,从而解决旋转问题,相关cpp代码,以及测试如下:

#include<iostream>
#include<vector>

using namespace std;
// In order to rotate the matrix in place, we make each cycle as a turn.
class Solution {
public:
    void rotate(vector<vector<int> >& matrix) {
        if (matrix.size() == 0) {
            return;
        }
        // The square edge length of each turn.
        int length = matrix.size() % 2 == 0? 0: 1;
        // The start position of each rotate.
        int start = matrix.size() / 2 - 1;
        int temp;
        for (; start >= 0; start --) {
            for (int i = 0; i <= length; i ++) {
                // Move the conrespond element to the proper position.
                temp = matrix[start][start + i];
                matrix[start][start + i] = matrix[start + length - i + 1][start];
                matrix[start + length - i + 1][start] = matrix[start + length + 1][start + length - i + 1];
                matrix[start + length + 1][start + length - i + 1] = matrix[start + i][start + length + 1];
                matrix[start + i][start + length + 1] = temp;
            }
            // Everty turn the edge increase length by 2.
            length += 2;
        }
    }
};

int main(int argc, char* argv[]) {
    Solution so;
    vector<vector<int> > test(5, vector<int>(5, 1));
    test[0][0] = 0;
    test[0][3] = 0;
    test[2][0] = 0;
    test[0][1] = 0;
    test[1][2] = 3;
    test[4][0] = 0;
    test[4][2] = 5;
    so.rotate(test);
    cout<<"result: "<<endl;
    for (int i = 0; i < test.size(); i ++) {
        for (int j = 0; j < test[0].size(); j ++) {
            cout<<test[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值