旋转一张图像

题目:

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?

原矩阵:  旋转后的矩阵:

分析:此题要求在原矩阵上完成旋转,因此可以采用交换的策略;先交换最外面一圈,然后是向内一圈。

具体代码如下:

void rotate(vector > &matrix) {
    int n=matrix.size();
    for(int i=0;i     {
        for(int j=i;j         {
            int tmp=matrix[i][j];
            matrix[i][j]=matrix[n-1-j][i];
            matrix[n-1-j][i]=matrix[n-1-i][n-1-j];
            matrix[n-1-i][n-1-j]=matrix[j][n-1-i];
            matrix[j][n-1-i]=tmp;
        }
    }
    return ;
}

你可能感兴趣的:(算法,矩阵,c++,code)