[Leetcode] spiral matrix II

Source: Internet
Author: User

Given an integerN, Generate a square matrix filled with elements from 1N2 in spiral order.

For example, givenN=3,

You shoshould return the following matrix:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
Class solution {public: vector <int> generatematrix (int n) {vector <int> V (n, 0); vector <int> res (n, v); int Col = (n + 1)/2-1; // The row and column number of the end point int ROW = n/2; int num = 1; int rowstart = 0, rowend = n-1, colstart = 0, colend = n-1; Int J = colstart, I = rowstart; while (1) {for (j = colstart; j <= colend; j ++) {res [I] [J] = num ++;} J = J-1; if (I = row & J = col) break; rowstart ++; j = colend; for (I = rowstart; I <= rowend; I ++) {res [I] [J] = num ++;} colend --; I = rowend; For (j = colend; j> = colstart; j --) {res [I] [J] = num ++;} J = J + 1; if (I = row & J = col) break; rowend --; j = colstart; for (I = rowend; I> = rowstart; I --) {res [I] [J] = num ++;} colstart ++; I = rowstart ;}// end while return res ;}};

 

[Leetcode] spiral matrix II

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.