From: http://blog.csdn.net/yhmhappy2006/article/details/2934435
I recently want to prepare for the test and interview, so I read the book "Programmer Interview Guide" and saw a interview question. I have never heard of it before, I spent a few minutes thinking about the rule. I did not find out the rule. After reading the answer, I gave the formula directly, but didn't say how to analyze it. So I checked it online, I found that the analysis in this article is very detailed, and I turned around.
The following data arrangement is a spiral queue
21 22 23 2425
20 7 8910
19 612 11
18 5 4 3 12
17 16 15 14 13
Let's see the following figure. The coordinates of point 1 are (0, 0), the X direction is right, and the Y direction is downward. For example, the coordinates of 7 are (-1,-1), 2 is (), and 3 is ). Program to input any coordinate point (x, y) and output the corresponding number.
In fact, there is a wrong question here. At the beginning, I was confused for a while, so I could not understand it all the time. In fact, the coordinates of 2 should be ), the Code is as follows:
# Include <iostream> # include <string> using namespace STD; # define ABS (A) (a)> 0? (A) :(-A) # define max (A, B) (a)> (B )? (A) :( B) int spiralval (INT X, int y) {int T = max (ABS (x), ABS (y )); int Vc = (T * 2 + 1) * (T * 2 + 1); int U; If (y =-T) // determine, point on which side of the four sides of the circle u = VC + (x + y); else if (x =-T) U = VC + (3 * x-y); else if (y = T) u = VC + (-X-5 * y ); elseu = VC + (-7 * X + Y); Return U;} int main () {int X, Y; For (y =-5; y <= 5; Y ++) {for (x =-5; x <= 5; X ++) printf ("% 5d", spiralval (x, y )); printf ("\ n") ;}cout <Endl; cout <"input x value:"; CIN> X; cout <"input y value :"; cin> Y; cout <"The result is" <spiralval (x, y); Return 0 ;}
Note that you must first judge y =-T, because when the number on the diagonal line on the upper right meets the requirements of two formulas, one is y =-t, X = T, but only y =-T is correct.
References:
1. http://blog.csdn.net/yhmhappy2006/article/details/2934435
2. http://hi.baidu.com/%D3%C0%BA%E3%D0%C4%B0% AE /blog/item/0a182724c5816f0b4c088d28.html