/*
螺旋队列
21 22.....
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
使用O(n)的时间和O(1)的空间输出长度为n的螺旋队列
设1的坐标为(0, 0);2的坐标为(1, 0);4的坐标为(0, 1)
*/
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int abs(int a){return a > 0 ? a : -a;}
int foo(int x, int y)
{
int t = max(abs(x), abs(y));
int u = t + t;
int v = u - 1;
v = v * v + u;
if(x == -t)
v += u + t - y;
else if(y == -t)
v += 3 * u + x - t;
else if(y == t)
v += t - x;
else
v += y - t;
return v;
}
int main()
{
int x, y;
for(y = -2; y <= 2; y ++)
{
for(x = -2; x <= 2; x ++)
{
printf("%5d", foo(x, y));
}
printf("\n");
}
return 0;
}
04-13
04-13