转自:http://blog.csdn.net/yhmhappy2006/article/details/2934435
最近要准备笔试和面试,所以看了一下《程序员面试宝典》这本书,看到一个面试题,要写螺旋队列,以前都没听过,我花几分种时间想了想,没找出其中的规律,看了一下答案是直接给出了公式,但没说是如何分析的,所以在网上查了查,发现这篇文章分析的很详细,就转过来了
下面的数据排列就是螺旋队列
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
看清以上数字排列的规律,设1点的坐标是(0,0),x方向向右为正,y方向向下为正。例如:7的坐标为(-1,-1),2的坐标为(0,1),3的坐标为(1,1)。编程实现输入任意一点坐标(x,y),输出所对应的数字。
其实这里题目有个错误的地方,刚开始,我也困惑了好一会,导致一直理解不过来,其实2的坐标应该是(1,0),这样才符合分析的公式,代码如下:
#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) //分别判断,点落在该圈4条边的哪条边上 u = vc+(x+y); else if (x == -t) u = vc+(3*x-y); else if (y == t) u = vc + (-x - 5*y); else u = 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; }
注意,一定要先判断y==-t,因为当在右上的对角线上的数字,满足两种公式要求,一种y==-t,一种x==t,但只有y==-t这种公式算出来的对角数字才是对的
参考资料:
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