48. Rotate Image

来源:互联网 发布:linux强制关闭tomcat 编辑:程序博客网 时间:2024/06/03 11:35

problem:

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?

首先沿着副对角线翻转一次,然后水平翻转一次即可。

class Solution {public:    void rotate(vector<vector<int>>& matrix) {        int i, j, temp;        int n = matrix.size(); // 图片大小        // 沿着副对角线反转        for(i=0; i<n; i++)        {            for(j=0; j<n-i; j++)            {                temp = matrix[i][j];                matrix[i][j] = matrix[n - 1 - j][n - 1 - i];                matrix[n - 1 - j][n - 1 - i] = temp;            }        }        // 沿着水平中线反转        for (int i = 0; i < n / 2; ++i){            for (int j = 0; j < n; ++j) {                temp = matrix[i][j];                matrix[i][j] = matrix[n - 1 - i][j];                matrix[n - 1 - i][j] = temp;            }        }    }};


0 0