[leetcode] Rotate Image

来源:互联网 发布:linux开发环境搭建 编辑:程序博客网 时间:2024/05/17 17: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?

思路:一层一层的旋转,由外到内

代码:

class Solution {public:    void rotate(vector<vector<int> > &matrix) {        if(matrix.size()==0) return;        int n=matrix.size();        for(int layer=0;layer<n/2;layer++){            int first=layer;            int last=n-layer-1;            for(int i=first;i<last;i++){                int offset=i-first;                int top=matrix[first][i];                matrix[first][i]=matrix[last-offset][first];                matrix[last-offset][first] = matrix[last][last - offset];                matrix[last][last - offset] = matrix[i][last];                matrix[i][last] = top;             }        }        return;    }};


0 0
原创粉丝点击