N阶方阵排列解法
时间:2010-09-12 来源:Ethanyen

#include <stdio.h>
const int ARR_LEN = 10;
const int Direction_start[4][2] ={{0,1},{1,-1},{1,0},{-1,1}}; //↓↗→↙,從前數到尾
int main(void) {
//std::cin>>ARR_LEN;
int count=ARR_LEN*ARR_LEN;
int Tcount=count+1;
int hcount=count>>1;//這個變數可以不要,直接寫在for迴圈裡即可。
int ARR_count=-1;
int *ARR=new int[count];
int XYEnd=ARR_LEN-1;
int X=0;
int Y=0;
for(int i=1;i<hcount+2;i++)
{
*(ARR+X*ARR_LEN+Y)=i;
*(ARR+count-i)=Tcount-i;
if(X==0 || Y==0 || X==XYEnd || Y==XYEnd)
{
ARR_count++;
if(ARR_count==4){ARR_count=0;}
}
X+=Direction_start[ARR_count][0];
Y+=Direction_start[ARR_count][1];
}
for (Y = 0; Y < ARR_LEN; Y ++) {
for (X = 0; X < ARR_LEN; X ++) {
printf("%2d ", *(ARR+X*ARR_LEN+Y));
}
printf("\n");
}
system("pause");
return 0;
}
时间过得很快,转瞬过了一年。这是当初的解法,速度大概接近黄晨的一倍快,从档案堆中找出这个解法之际,我才发觉竟还有一个更精妙的解法,速度应该还可再提升一倍。
如果你正面临着某些算法必须极端讲求速度时,可以在这里留言,描述请尽量详细,甚至留下自己的解法。我一得空闲,便会尝试解题。
关于这一题的解题思维如下:
1 |
3 |
4 |
2 |
5 |
8 |
6 |
7 |
9 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
由于「相称」性规则,每一组的位置是固定的,加总也都是10,如此只需完成一次计算,再加上一个减号运算就能配置出一组。如此效率自然提升接近一倍。
相关阅读 更多 +