Rotate the image 90 degrees

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.