Title: Given an image represented by the n*n matrix, where each pixel is 4 bytes in size, write a method that rotates the image 90 degrees. Can you do this without taking up extra memory space?
So, how do you exchange these four sides? One approach is to copy the above into an array, then move the left side to the top, move the bottom to the left, and so on. This takes up the O (N) memory space. But it's not really necessary,
A better approach would be to exchange them by one of the indexes. The following are the specific practices:
For i = 0 to n
temp = Top[i];
Top[i] = Left[i];
Left[i] = Bottom[i];
Bottom[i] = Right[i];
Right[i] = temp;
Start from the outermost layer and perform the above exchange on each layer. (Alternatively, you can start with the inner layer and go outward from layer to row)
The implementation code is as follows:
void rotate (int **matrix,int n)
{
for (int layer = 0; layer < N/2; ++layer)
{
int first = layer;
int last = n-1-layer;
for (int i = first; I < last;++i)
{
int offset = I-first;
Store Top
int top = Matrix[first][i];
Left to top
Matrix[first][i] = Matrix[last-offset][first];
Down to the left
Matrix[last-offset][first] = Matrix[last][last-offset];
Right to bottom
Matrix[last][last-offset] = Matrix[i][last];
Up to the right
Matrix[i][last] = top;
}
}
}
The time complexity of this algorithm is O (N2);(N2: Represents the square of N).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Rotate the image 90 degrees