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?
分析:
通過實際數據分析,通過兩個步驟的元素交換可實現目標:
按照主對角線,將對稱元素交換
按照列,將對稱列元素全部交換
即可達到,使得二維矩陣,本地旋轉90個角度。
代碼如下:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size();
//一,對角線對換
for(int i=0;i<n-1;i++)//列
{
for(int j=0;j<n-1-i;j++)//行
{
int tmp=matrix[j][i];
matrix[j][i]=matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j]=tmp;
}
}
//二,水平線對換
for(int i=0;i<n;i++)//列
{
for(int j=0;j<n/2;j++)//行
{
int tmp=matrix[j][i];
matrix[j][i]=matrix[n-1-j][i];
matrix[n-1-j][i]=tmp;
}
}
}
};
注:本博文爲EbowTang原創,後續可能繼續更新本文。如果轉載,請務必複製本條信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51588641
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode題解索引:http://blog.csdn.net/ebowtang/article/details/50668895