LeetCode OJ: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?
题目要就地算法,那么可以通过折叠矩阵上下以及斜对角线折叠来实现,代码如下:

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int>>& matrix) {
 4         int sz = matrix.size();   
 5         if(!sz) return;
 6         for(int i = 0; i < sz; ++i){
 7             for(int begin = 0, end = sz - 1; begin < end; ++begin, --end){
 8                 swap(matrix[begin][i], matrix[end][i]);
 9             }
10         }
11         for(int i = 0; i < sz; ++i){
12             for(int j = i; j < sz; ++j){
13                 swap(matrix[i][j], matrix[j][i]);
14             }
15         }
16     }
17 };

同样的通过乘以一个矩阵的方法当然也可以实现,不过那不是in-place算法。

 

posted @ 2015-10-29 20:34  eversliver  阅读(230)  评论(0编辑  收藏  举报