Topic
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?
Analysis
Locally makes the two-dimensional matrix rotate 90 angles.
Through the actual data analysis, the target can be achieved by exchanging elements in two steps:
- The symmetric elements are exchanged according to the main diagonal
- All symmetric column elements are exchanged by column
Can be achieved, so that the two-dimensional matrix, the local rotation of 90 angles.
AC Code
classSolution { Public:voidRotate vector<vector<int>>& Matrix) {if(Matrix.empty ())return;intn = matrix.size ();//First, swap elements along the main diagonal for(inti =0; I < n; i++) { for(intj =0; J <= I; J + +) Swap (Matrix[i][j], matrix[j][i]); } for(inti =0, j = n-1; I < J; i++, j--) { for(intK =0; K < n; k++) Swap (Matrix[k][i], matrix[k][j]); } }};
GitHub test Program source code
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode (Rotate) Image