Rotate Image

来源:互联网 发布:网络科学导论讲义 编辑:程序博客网 时间:2024/04/29 13:41

Description:
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?

//首先沿着副对角线翻转一次,然后沿着水平中线翻转一次;//或者沿着水平中线翻转一次,然后沿着副对角线翻转一次#include <iostream>#include <algorithm>using namespace std;class Solution{public:    void rotateImage(const int n, int A[3][3])    {        for (int i=0; i < n; ++i)   //沿着副对角线翻转        {            for (int j=0; j < n/2 ; ++j)            {                swap(A[i][j],A[n-1-j][n-1-i]);            }        }        cout<<"沿着对角线翻转后: "<<endl;        //沿着对角线翻转后效果        for (int i=0; i < 3 ; ++i)        {            for (int j=0; j < 3 ; ++j)            {                cout<<A[i][j]<<" ";            }            cout<<endl;        }        for (int i=0; i < n/2 ; ++i)        {           for (int j=0 ; j < n ; ++j)           {               swap(A[i][j],A[n-1-i][j]);           }        }        cout<<"沿着水平中线翻转后: "<<endl;        //沿着水平中线翻转后        for (int i=0; i < n ; ++i)        {            for (int j=0; j < n ; ++j)            {                cout<<A[i][j]<<" ";            }            cout<<endl;        }    }};int main(){    const int n = 3;    int A[n][n] = {{1,2,3},{4,5,6},{7,8,9}};    for (int i=0; i < 3 ; ++i)    {        for (int j=0; j < 3 ; ++j)        {            cout<<A[i][j]<<" ";        }        cout<<endl;    }    Solution solution;    solution.rotateImage(n,A);    return 0;}

这里写图片描述

0 0
原创粉丝点击