"Primary algorithm" 11. Rotate the image

Source: Internet
Author: User

Topic:

given a nxn, a two-dimensional matrix represents an image. Rotate the image clockwise -degree. Note: You must rotate the image in place, which means you need to modify the input two-dimensional matrix directly. Do not use another matrix to rotate the image. Example1: Given the matrix= [  [1,2,3],  [4,5,6],  [7,8,9] ], rotate the input matrix in place so that it becomes: [[7,4,1],  [8,5,2],  [9,6,3]] Example2: Given the matrix=[  [ 5,1,9, One],  [ 2,4,8,Ten],  [ -,3,6,7],  [ the, -, A, -] ], rotate the input matrix in place so that it becomes: [[ the, -,2,5],  [ -,3,4,1],  [ A,6,8,9],  [ -,7,Ten, One]]

Problem Solving Ideas:

1. Rotate each of these layers:

classSolution { Public:   voidRotate (vector<vector<int> > &matrix) {        intn =matrix.size ();  for(inti =0; I < n/2; ++i) { for(intj = i; J < N-1I ++j) {intTMP =Matrix[i][j]; MATRIX[I][J]= Matrix[n-1-J]                [i]; Matrix[n-1-J][i] = matrix[n-1-I][n-1-J]; Matrix[n-1-I][n-1-j] = Matrix[j][n-1-i]; Matrix[j][n-1-I] =tmp; }        }    }};

2. Transpose the matrix, then swap right and left.

class Solution {public:    void rotate (vector<vector<int> > &Matrix) {         int n = matrix.size ();          for (int0; i < n; + +i)            {for (int1; j < n; ++<
   
     C20>J) {                swap (matrix[i][j], matrix[j][i]);            }            Reverse (Matrix[i].begin (), Matrix[i].end ());}}           ;
   

Primary algorithm 11. Rotate the image

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.