You are given a n x n 2D matrix representing an image.
Rotate the image by degrees (clockwise).
Follow up:
Could do this in-place?
Thought: My idea, first along the diagonal symmetry, and then left and right symmetry.
voidRotateint**matrix,intN) {//first diagonally symmetrical for(inti =0; I < n; i++) { for(intj =0; J < I; J + +) { intTMP =Matrix[i][j]; MATRIX[I][J]=Matrix[j][i]; Matrix[j][i]=tmp; } } //and then the symmetry around for(intc =0; C < (n +1) /2; C++) { for(intR =0; R < N; r++) { intTMP =Matrix[r][c]; MATRIX[R][C]= Matrix[r][n-c-1]; Matrix[r][nC1] =tmp; } } return;}
Great God one step thought: find each circle to each other clockwise exchange of 4 positions, exchange.
classSolution { Public: voidRotate (vector<vector<int> > &matrix) { intn =matrix.size (); if(n<=1)return; for(inti =0; i!=n/2; i++)//rows of laps { for(intj = 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]); }}} inlinevoidSwapint&a,int&b) {a= B +A; b= A-b; A= A-b; }};
"Leetcode" Rotate Image (middle)