Rotate Image

来源:互联网 发布:江苏软件考试网 编辑:程序博客网 时间:2024/04/26 01:49

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 s = matrix.size() - 1;                                                                                                                                      for (int n = s, c = 0; n > 0; n -= 2, ++c) {                                        int tmp;                                                                                                                                                        for (int i = 0; i < n; ++i) {                                                       // clockwise                                                                    tmp = matrix[c][i + c];                                                         matrix[c][i + c] = matrix[s - i - c][c];                                        matrix[s - i - c][c] = matrix[s - c][s - i - c];                                matrix[s - c][s - i - c] = matrix[i + c][s - c];                                matrix[i + c][s - c] = tmp;                                                                                                                                     // anticlockwise                                                                /*tmp = matrix[c][i + c];                                                       matrix[c][i + c] = matrix[i + c][s - c];                                        matrix[i + c][s - c] = matrix[s - c][s - i - c];                                matrix[s - c][s - i - c] = matrix[s - i - c][c];                                matrix[s - i - c][c] = tmp;*/                                               // print here to observ how it works                                }                                                                           }                                                                           }                    };


0 0