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?
刚开始没有思路,但是自己举了几个简单的栗子才看出规律:需要一圈儿一圈儿的变换位置。有两层for循环:外层控制圈儿数;内层控制交换的元素位置。每一次都有四个元素需要交换。代码如下:
class Solution { public: void rotate(vector<vector<int> > &matrix) { size_t len_matrix = matrix.size(); if(len_matrix == 0) return; for(size_t i = 0; i < len_matrix / 2; i++) { for(size_t j = i; j < len_matrix - i - 1; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[len_matrix - j - 1][i]; matrix[len_matrix - j - 1][i] = matrix[len_matrix - i - 1][len_matrix - j - 1]; matrix[len_matrix - i - 1][len_matrix - j - 1] = matrix[j][len_matrix - i - 1]; matrix[j][len_matrix - i - 1] = temp; } } } };
原文地址:http://blog.csdn.net/u012118523/article/details/24843535