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?
要求不能另開空間,一開始理解錯了,後來畫圖明白了
解題思路:
首先以對角線爲軸對稱交換,再以中間列(如果有的話)爲軸對稱交換
a b c d
e f g h
i j k l
m n o p

a e i m
b f j n
c g k o
d h l p

m i e a
n j f b
o k g c
p l h d

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        if (matrix.empty()) 
            return;
        int n = matrix.size(), tmp;

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
        for (int i = 0; i < n/2; ++i) {
            for (int j = 0; j < n; ++j) {
                tmp = matrix[i][j];
                matrix[i][j] = matrix[n-1-i][j];
                matrix[n-1-i][j] = tmp;
            }
        }
        return;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章