第十四周:48. Rotate Image

    xiaoxiao2021-03-25  69

    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?

    思路就是先举个例子,加入一个3*3的矩阵:

    123456789   经过90°转换后变成:

    741852963 于是发现以下的关系:a[0][0] = a[2][0];a[0][1] = a[2][0];a[0][2] =a[0][0];a[1][0] =a[2][1];a[1][1] = a[1][1];a[1][2] =a[2][1];a[2][0] = a[2][2];a[2][1] = a[1][2];a[2][2] =a[0][2];通过以上观察,发现这样一个规律: 对于n * n 的2维矩阵,a[i][j]-> a[j][n-1-i].

    AC:

    class Solution { public: void rotate(vector<vector<int>>& matrix) { int i,j,temp; int n=matrix.size(); for(i = 0;i < n/2;++i) { for (j = i;j < n-1-i;++j) { temp = matrix[j][n-i-1]; matrix[j][n-i-1] = matrix[i][j]; matrix[i][j] = matrix[n-j-1][i]; matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = temp; } } } };

    转载请注明原文地址: https://ju.6miu.com/read-37352.html

    最新回复(0)