【Rotate Image】cpp
题目:
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) { const unsigned int len = matrix.size(); if ( len < 2 ) return; for ( int row = 0; row < len; ++row) { for (int col = 0; col < len-1-row; ++col) { std::swap(matrix[row][col], matrix[len-1-col][len-1-row]); } } for ( int row = 0; row < len/2; ++row) { for ( int col = 0; col < len; ++col) { std::swap(matrix[row][col], matrix[len-1-row][col]); } } } };
Tips:
1. 算法:先沿着副对角线(右上到左下)swap元素;再沿着水平中轴线swap元素
2. 注意循环遍历时的结束条件,不要做无谓的遍历
=============================================
图像旋转90°的算法技巧:先副对角线对折;再沿着水平中轴对折。代码一次AC。
class Solution { public: void rotate(vector<vector<int>>& matrix) { const int N = matrix.size(); if ( N<2 ) return; for ( int i=0; i<N; ++i ) { for ( int j=0; j<N-i; ++j ) { std::swap(matrix[i][j], matrix[N-1-j][N-1-i]); } } for ( int i=0; i<N/2; ++i) { for ( int j=0; j<N; ++j) { std::swap(matrix[i][j], matrix[N-1-i][j]); } } } };