5 4 3
6 1 2
7 8 9
请问这题的算法是?????
#include <stdio.h>
#include <conio.h>
const int N=8;
const int M=8;
main()
{ int a[N][M];
int k=0, m=0, v=0;
int direction = 0; //0:right; 1:down; 2:left; 3:up
while(v<=N*M)
{ a[k][m] = v;
v++;
switch(direction)
{
case 0: m++;
if(m==M-1-k)
direction = 1;
break;
case 1: k++;
if(k==N-1-(M-1-m))
direction = 2;
break;
case 2: m--;
if(m==N-1-k)
direction = 3;
break;
case 3: k--;
if(k==1+m)
direction = 0;
break;
}
}
for(k=0; k<N; k++)
{
for(m=0; m<M; m++)
printf("%3d", a[k][m]);
printf("\n");
}
}
看一看这个程序或许对你有点启发.
(别人发的帖子,我觉得写得很好,放到电脑上的;看到你的题目要求就想起了.呵呵)
根据2楼改的 ,起始方向向左,你自己改一下吧。把 N M a[*][*] 值换成 3,5,7,9,11 v==N*M
#include <stdio.h>
#include <conio.h>
const int N=9;
const int M=9;
int main()
{ int a[9][9];
int k=0, m=0, v=81;
int direction = 0; /* 0:right; 1:down; 2:left; 3:up */
while(v>=1)
{ a[k][m] = v;
v--;
switch(direction)
{
case 0: m++;
if(m==M-1-k)
direction = 1;
break;
case 1: k++;
if(k==N-1-(M-1-m))
direction = 2;
break;
case 2: m--;
if(m==N-1-k)
direction = 3;
break;
case 3: k--;
if(k==1+m)
direction = 0;
break;
}
}
for(k=0; k<N; k++)
{
for(m=0; m<M; m++)
printf("%3d", a[k][m]);
printf("\n");
}
getch();
return 0;
}
[此贴子已经被作者于2007-5-19 13:15:22编辑过]