输入n ,打印出n*n的螺旋矩阵(算法)

来源:互联网 发布:网络用语猜成语 编辑:程序博客网 时间:2024/05/22 02:18

如:

n = 2;

输出:

1  2

4  3 

void fun(int n){        int a[n][n];        int startx = 0;        int endx = n - 1;        int starty = 0;        int endy = n - 1;        int count = 1;        while(1)        {                for(int i = startx; i <= endx; i++)                        a[starty][i] = count++;                if(++starty <= endy)                for(int i = starty; i <= endy; i++)                        a[i][endx] = count++;                if(--endx >= startx)                for(int i = endx; i >= startx; i--)                        a[endy][i] = count++;                if(--endy >= starty)                for(int i = endy; i >= starty; i--)                        a[i][startx] = count++;                if(++startx > endx)                        break;        }        for(int i = 0; i < n; i++)        {                for(int j = 0; j < n; j++)                {                        printf("%d ",a[i][j]);                }                printf("\n");        }}


0 0
原创粉丝点击