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.