# LeetCode [Array]: Rotate Image

Source: Internet
Author: User
Tags rotate image

LeetCode [Array]: Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise ).
Cocould you do this in-place?

Refer to the LeetCode [Array]: Spiral Matrix II iteration idea. First, complete the rotation of the outermost ring, and then rotate the inner ring in sequence. My C ++ code is as follows:

```void rotate(vector

> &matrix) {    int beginRow = 0, endRow = matrix.size() - 1, beginCol = 0, endCol = matrix[0].size() - 1;    while (beginRow <= endRow && beginCol <= endCol) {        for (int i = 0; i < endCol - beginCol; ++i) {            int tmp                               = matrix[beginRow    ][beginCol + i];            matrix[beginRow    ][beginCol + i] = matrix[  endRow - i][beginCol      ];            matrix[  endRow - i][beginCol    ] = matrix[  endRow    ][  endCol - i];            matrix[  endRow    ][  endCol - i] = matrix[beginRow + i][  endCol    ];            matrix[beginRow + i][  endCol    ] = tmp;        }        ++beginRow; --endRow;        ++beginCol; --endCol;    }}
```

The idea of seeing a strange solution on Discuss is: first put the matrix upside down, and then rotate along the diagonal line between the top left and the bottom right, its C ++ code implementation is very concise:

```void rotate(vector

> &matrix) {    reverse(matrix.begin(), matrix.end());    for (unsigned i = 0; i < matrix.size(); ++i)        for (unsigned j = i+1; j < matrix[i].size(); ++j)            swap (matrix[i][j], matrix[j][i]);}
```

Related Keywords:

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.