Spiral Matrix II

Source: Internet
Author: User

Http://blog.csdn.net/shiquxinkong

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n =3,

You shoshould return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

We walked around as required, just like peeling oranges, and We stripped the upper and lower sides of the skin, so this circle is okay, but here we dialed a layer of the dial. Okay, see the figure:


The same color indicates the starting point of each layer, and red indicates the starting point of each layer. This instance has three layers. As mentioned above, the instance is dialed in the order of top, bottom, and left, there are old and old, right and right siblings.

How many layers do I need to allocate? The three layers above are marked with eyes. Right, it should be (n + 1)/2. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + Ly9DT0RFPC9wPgo8cD48cHJlIGNsYXNzPQ = "brush: java;"> class Solution {public: vector > GenerateMatrix (int n) {vector > Vivec (n, vector (N, 0); if (n <= 0) return vivec; int start_num = 1; // up, right, down and left construct a circle. int layer = 0; while (layer <(1 + n)/2) {// up for (int I = layer; I <n-layer; ++ I) {vivec [layer] [I] = start_num ++;} // right for (int I = layer + 1; I <n-layer; ++ I) {vivec [I] [n-layer-1] = start_num ++;} // down for (int I = n-layer-2; I> = layer; -- I) {vivec [n-layer-1] [I] = start_num ++;} // left for (int I = n-layer-2; I> = layer + 1; -- I) {vivec [I] [layer] = start_num ++;} layer ++;} return vivec ;}};Note that the starting boundary of each layer is controlled.

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.