数据结构之螺旋对列
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static int foo(int x, int y)
{
//螺旋的层数
int layer = Math.Max(Math.Abs(x), Math.Abs(y));
//螺旋右上角的数
int topRight = (layer * 2 + 1) * (layer * 2 + 1);
int result = 0;
//算法的精髓在于找到右上角的数以后,开始找十字花的数,也就是找到a[0][0]的右侧a[0][1],a[1][0],a[0][-1],a[-1][0]的值
if (y == -layer) //上面一层
{
result = topRight - 1 * layer + x;
}
else if (x == -layer) //左边一层
{
result = topRight - 3 * layer - y;
}
else if (y == layer)
{
result = topRight - 5 * layer - x;
}
else if (x == layer)
{
result = topRight - 7 * layer + y;
}
return result;
}
{
//螺旋的层数
int layer = Math.Max(Math.Abs(x), Math.Abs(y));
//螺旋右上角的数
int topRight = (layer * 2 + 1) * (layer * 2 + 1);
int result = 0;
//算法的精髓在于找到右上角的数以后,开始找十字花的数,也就是找到a[0][0]的右侧a[0][1],a[1][0],a[0][-1],a[-1][0]的值
if (y == -layer) //上面一层
{
result = topRight - 1 * layer + x;
}
else if (x == -layer) //左边一层
{
result = topRight - 3 * layer - y;
}
else if (y == layer)
{
result = topRight - 5 * layer - x;
}
else if (x == layer)
{
result = topRight - 7 * layer + y;
}
return result;
}