Rotate Image

题目名称
Rotate Image—LeetCode链接

描述
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?

分析
  题目中要求我们在原来的二维数组上进行修改,不要使用额外的空间。代码是参考别人的,我这里做一下解释:

Rotate Image_第1张图片

  用到两层循环,最外层循环用来交换每一圈的数组值,因为每一圈上的数据交换都相同规律,所以内层循环用来交换一圈上所有需要顺时针旋转90°的值。

C++代码

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int a = 0;
        int b = n-1;
        while(a<b){
            for(int i=0;i<(b-a);++i){
                swap(matrix[a][a+i], matrix[a+i][b]);
                swap(matrix[a][a+i], matrix[b][b-i]);
                swap(matrix[a][a+i], matrix[b-i][a]);
            }
            ++a;
            --b;
        }
    }
};

总结
  一开始想找出所有位置经顺时针旋转90°之后的位置,但是没有找到通用的,这道题目也难在这里。

你可能感兴趣的:(LeetCode,二维数组,Matrix)