首页 > 其他 > 详细

矩阵翻转算法

时间:2014-03-14 11:36:05      阅读:543      评论:0      收藏:0      [点我收藏+]

题目:

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes

write a method to rotate the image by 90 degrees. Can you do this in place?

解决思想:

顺时针:先将矩阵转置   再将依次将各行首尾互换

逆时针:先将矩阵转置   再将依次将各列首尾互换

以4X4矩阵逆时针旋转90°为例:

#include <iostream>
using namespace std;

void swap(int &a, int &b){
    int t = a;
    a = b;
    b = t;
}
void transpose(int a[][4], int n){
    for(int i=0; i<n; ++i)
        for(int j=i+1; j<n; ++j)
            swap(a[i][j], a[j][i]);
    for(int i=0; i<n/2; ++i)
        for(int j=0; j<n; ++j)
            swap(a[i][j], a[n-1-i][j]);
}
int main(){
    int a[4][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    for(int i=0; i<4; ++i){
        for(int j=0; j<4; ++j)
            cout<<a[i][j]<<" ";
        cout<<endl;
    }
    cout<<endl;
    transpose(a, 4);
    for(int i=0; i<4; ++i){
        for(int j=0; j<4; ++j)
            cout<<a[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}




矩阵翻转算法,布布扣,bubuko.com

矩阵翻转算法

原文:http://blog.csdn.net/smileteo/article/details/21202431

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