48. Rotate Image

来源:互联网 发布:java ee api 编辑:程序博客网 时间:2024/06/05 08:58

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<vector>using namespace std;class Solution {public:    void rotate(vector<vector<int> >& matrix)     {        int i , j , n;        n=matrix.size();        if(n == 0 || n == 1)            return ;        for(i = 0 ; i < n ; i++)        {            for(j=i+1;j<n;j++)                swap(matrix[i][j],matrix[j][i]);        }        for(i=0;i<n/2;i++)        {            for(j=0;j<n;j++)                swap(matrix[j][i],matrix[j][n-1-i]);        }    }};int main(){    int N,i,j,x;    vector<vector<int> >matrix;    vector<int>temp;    cin>>N;    for(i=0;i<N;i++)        matrix.push_back(temp);    for(i=0;i<N;i++)        for(j=0;j<N;j++)        {            cin>>x;            matrix[i].push_back(x);        }    Solution solve;    solve.rotate(matrix);    for(i=0;i<N;i++)    {        for(j=0;j<N;j++)            cout<<matrix[i][j]<<' ';        cout<<endl;    }    return 0;}
0 0
原创粉丝点击