您的位置:首页 > 其它

螺旋矩阵

2013-11-21 10:58 323 查看
    下面是一个5×5的螺旋方阵,试编程打印出此形式的n×n(n<10)阶的方阵。
1   2   3   4   5
16  17  18  19  6
15  24  25  20  7
14  23  22  21  8
13  12  11  10  9

 

#include<stdio.h>
#define N 5
//螺旋矩阵
int main()
{
int count,i,j;
int direction=1; //分为左、下、上、右四个方向用1,2,3,4代替
int array

={0};

i=0;
j=0;
for(count=1;count<=N*N;count++)
{
array[i][j]=count;

//确定下一个方向
if(direction==1)
{
if (j==N-1 || array[i][j+1]!=0)
direction=2;
}else
{
if (direction==2)
{
if (i==N-1 || array[i+1][j]!=0)
direction=3;
}else
{
if(direction==3)
{
if (j==0 || array[i][j-1]!=0)
direction=4;
}else
{
if (i==0 || array[i-1][j]!=0)
direction=1;
}
}
}

//根据方向决定下一个坐标

switch(direction)
{
case 1:
j++; break;
case 2:
i++; break;
case 3:
j--; break;
case 4:
i--; break;
}
}

//输出
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf("%3d", array[i][j]);
printf("\n");
}

return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: