【leetcode】Rotate Image(middle)
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?
思路:我的思路,先沿对角线对称,再左右对称。
void rotate(int **matrix, int n) { //先沿对角线对称 for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } //再左右对称 for(int c = 0; c < (n + 1) / 2; c++) { for(int r = 0; r < n; r++) { int tmp = matrix[r][c]; matrix[r][c] = matrix[r][n - c - 1]; matrix[r][n - c - 1] = tmp; } } return; }
大神一步到位的思路:找到每个圈要相互顺时针交换的4个位置,交换。
class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); if(n<=1) return; for(int i = 0; i!=n/2;i++) //行 圈数 { for(int j = i;j!=n-1-i;j++) { swap(matrix[i][j],matrix[j][n-1-i]); swap(matrix[n-1-j][i],matrix[i][j]); swap(matrix[n-1-i][n-1-j],matrix[n-1-j][i]); } } } inline void swap(int &a,int &b) { a = b+a; b = a-b; a = a-b; } };