leetcode 48. Rotate image
Question stem
Given an n × n two-dimensional matrix represents an image.
Rotate the image 90 degrees clockwise.
Note:
You must rotate the image in place, which means you need to directly modify the input two-dimensional matrix. Please do not use another matrix to rotate the image.
Example 1:
Given matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in place to make it:
[
[7,4, 1],
[8,5,2],
[9,6,3]
]
Example 2:
Given matrix =
[
[5, 1, 9,11],
[2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
], the
original Rotate the input matrix so that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
answer
Flip step by step from the outside to the inside, flip one circle of the square at a time, pay attention to the exchange and coverage of elements
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
if(n == 1){
return;
}
int head,tail;
//按圈遍历,从外到内
for(int i = 0 ; i <= n / 2 ; ++i){
head = i;
tail = n - 1 - i;
//(0,2) <- (2,0)
//从左上角开始交换,起始坐标(i,head)
while(head < tail){
//cout<<"("<<i<<","<<head<<")"<<endl;
int preValue = matrix[n - 1 - head][i];
int nowRowIndex = i;
int nowColIndex = head;
for(int j = 0 ; j < 4 ; ++j){
int temp = matrix[nowRowIndex][nowColIndex];
matrix[nowRowIndex][nowColIndex] = preValue;
preValue = temp;
temp = nowColIndex;
nowColIndex = n - 1 - nowRowIndex;
nowRowIndex = temp;
}
head++;
}
}
return;
}
};
Another method is to first transpose and then flip horizontally. If you want to report, you can implement it without writing code.