Topic
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by degrees. Can does this in place?
An image is represented as a matrix of nxn, each pixel in the image is 4 bytes, and a function is written to rotate the image 90 degrees. Can you operate in situ? (i.e. no additional storage space)
Answer
Let's say you want to rotate the image counterclockwise 90 degrees, clockwise is a good idea. If the original image looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Then the 90-degree counterclockwise rotation of the figure should be:
4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13
How do we operate in situ to achieve the above effect? Can go in two steps. The first step is to exchange the symmetric elements on both sides of the main diagonal, and the second step is to exchange the line I and n-1-i, which results in the result. Look at the diagram: (if it is clockwise, the first exchange/diagonal side of the symmetric elements, the second step to exchange the line I and line n-1-i, that is, the result is obtained.) )
原图: 第一步操作后: 第二步操作后:1 2 3 4 1 5 9 13 4 8 12 165 6 7 8 2 6 10 14 3 7 11 159 10 11 12 3 7 11 15 2 6 10 1413 14 15 16 4 8 12 16 1 5 9 13
The code for 90 degrees clockwise and 90 degrees counterclockwise is as follows:
#include <iostream>using namespace STD;voidSwapint*a,int*B) {intt = *a; *a = *b; *b = t;}///These 2 switching functions, choose one, I just want to demonstrate that they achieve the same resultvoidSWAP2 (int&a,int&B) {intt = A; A = b; b = t;}//ClockwisevoidClockwise (inta[][4],intN) { for(intI=0; i<n; ++i) for(intj=0; j<n-i; ++J) Swap (A[i][j], a[n-1-j][n-1-I.]); for(intI=0; i<n/2; ++i) for(intj=0; j<n; ++J) Swap (A[i][j], a[n-1-I][J]);}//Counter-clockwisevoidTranspose (inta[][4],intN) { for(intI=0; i<n; ++i) for(intj=i+1; j<n; ++J) Swap (&a[i][j], &a[j][i]); for(intI=0; i<n/2; ++i) for(intj=0; j<n; ++J) Swap (&a[i][j], &a[n-1-I][J]);}intMain () {inta[4][4] = { {1,2,3,4}, {5,6,7,8}, {9,Ten, One, A}, { -, -, the, -} }; for(intI=0; i<4; ++i) { for(intj=0; j<4; ++J)cout<<a[i][j]<<" ";cout<<endl; }cout<<endl; Transpose (A,4);cout<<"Turn counterclockwise 90 degrees"<<endl; for(intI=0; i<4; ++i) { for(intj=0; j<4; ++J)cout<<a[i][j]<<" ";cout<<endl; }cout<<endl; A = {{1,2,3,4}, {5,6,7,8}, {9,Ten, One, A}, { -, -, the, -} }; for(intI=0; i<4; ++i) { for(intj=0; j<4; ++J)cout<<a[i][j]<<" ";cout<<endl; } clockwise (A,4);cout<<endl;cout<<"Turn 90 degrees clockwise."<<endl; for(intI=0; i<4; ++i) { for(intj=0; j<4; ++J)cout<<a[i][j]<<" ";cout<<endl; }return 0;}
Output Result:
Classic algorithm interview topics (1.6)