荣誉版主
- 积分
- -2403
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-5-4
- 最后登录
- 1970-1-1
|
关键是构造一个函数原型如:int GetValue(int n, int i, int j)
通过 O(1)的时间复杂度获取”逻辑“数组上的a[i,j]的值:
int GetValue(int n, int i, int j)
{
assert(n>0 && i<n && j<n);
int x = n/2;
int y = n/2;
if (n%2 == 0)
x--;
if (x == i && y == j) return 1;
bool bXDec = false;
bool bYDec = true;
int nSteps = 1;
int nRet = 1;
while (nSteps <= n && nRet <= n*n)
{
//calculate each step
int nLeftX = nSteps;
int nLeftY = nSteps;
while (0 != nLeftY)
{
bYDec ? y-- : y++;
nRet++;
if (i == x && j == y) return nRet;
nLeftY--;
}
while (0 != nLeftX)
{
bXDec ? x-- : x++;
nRet++;
if (i == x && j == y) return nRet;
nLeftX--;
}
nSteps++;
bXDec = !bXDec;
bYDec = !bYDec;
}
return -1;
}
void PrintSpiral(int n)
{
assert(n>0);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout<<GetValue(n, i, j)<<" ";
cout<<endl;
}
} |
|