标签:
题目:
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. 注意循环遍历时的结束条件,不要做无谓的遍历
标签:
原文地址:http://www.cnblogs.com/xbf9xbf/p/4457942.html