題目:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise). (Medium)

Follow up:
Could you do this in-place?

分析:

就是在紙上畫一畫找到對應關係即可, newMatrix[i][j] = matrix[n - 1 - j][i];

所以簡單的方法就是開一個新陣列,按照對應關係填入新陣列,再拷貝回原來的陣列。

程式碼:

 class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
vector<vector<int>> temp = matrix;
for (int i = ; i < temp.size(); ++i) {
for (int j = ; j < temp[].size(); ++j) {
temp[i][j] = matrix[temp.size() - - j][i];
}
}
for (int i = ; i < matrix.size(); ++i) {
for (int j = ; j < matrix[].size(); ++j) {
matrix[i][j] = temp[i][j];
}
}
return;
}
};

題目中的follow-up,要in-place,考慮原陣列上如何處理。

要在原陣列上處理區域性交換感覺就不好想了(會交換完丟元素),把陣列整體一起處理好一些。

再觀察對應關係,只需要橫縱座標先顛倒,然後縱座標上下翻轉即可。

程式碼:

 class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
for (int i = ; i < matrix.size(); ++i) {
for (int j = ; j < i; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
for (int j = ; j < matrix.size() / ; ++j) {
for (int i = ; i < matrix[].size(); ++i) {
swap(matrix[i][j], matrix[i][matrix.size() - - j]);
}
}
return;
}
};