LeetCode Rotate Image

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 n = matrix.size();
        int end = n / 2;
        for (int i=0; i<end; i++) {
            for (int j=i; j < n - i - 1; j++) {
                int a = matrix[i][j];
                int b = matrix[j][n-1-i];
                int c = matrix[n-1-i][n-1-j];
                int d = matrix[n-1-j][i];
                matrix[i][j] = d;
                matrix[j][n-1-i] = a;
                matrix[n-1-i][n-1-j] = b;
                matrix[n-1-j][i] = c;
            }
        }
    }
};

水一发

更简单的方法:

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        for (int i=0; i<n; i++) {
            for (int j=0; j<i; j++) {
                swap(matrix[i][j], matrix[j][i]);
            }
        }
        for (int i=0; i<n; i++) {
            reverse(matrix[i].begin(), matrix[i].end());
        }
    }
};

 

posted @ 2014-07-19 00:52  卖程序的小歪  阅读(152)  评论(0编辑  收藏  举报