C实现蛇形矩阵 | LSABLOG

首页 » Program » C/C++ » 正文

C实现蛇形矩阵

思路是利用二维数组存元素,先存0圈,再到1圈,2圈,3圈…………
控制好每一条边的元素就可以了

#include <stdio.h>
int main()
{
    int SnakeMatrix[26][26];
    int r,count = 1;
    int x,y;
    int n,i,j,r1;
    while (scanf("%d",&n)!=EOF)
        {
            if (n==1)
                {
                    SnakeMatrix[0][0] = count;
                    printf("%d\n",SnakeMatrix[0][0]);
                }
            else
                {
                    r = n / 2;   //圈数
                    for (r1=0; r1<r; r1++) //控制圈
                        {
                            for (y=r1; y<n-r1; y++) //控制上边
                                {
                                    x = r1;
                                    SnakeMatrix[x][y] = count;
                                    count++;
                                }
                            for (x=r1+1; x<n-r1-1; x++) //控制右边
                                {
                                    y = n - r1 - 1;
                                    SnakeMatrix[x][y] = count;
                                    count++;
                                }
                            for (y=n-r1-1; y>=r1; y--) //控制下边
                                {
                                    x = n - r1 - 1;
                                    SnakeMatrix[x][y] = count;
                                    count++;
                                }
                            for (x=n-r1-1-1; x>r1; x--) //控制左边
                                {
                                    y = r1;
                                    SnakeMatrix[x][y] = count;
                                    count++;
                                }
                        }
                    if (n%2!=0) SnakeMatrix[n/2][n/2] = count;  //奇数圈则在中间补上
                    for (i=0; i<n; i++)
                        {
                            for (j=0; j<n; j++)
                                {
                                    if (j==n-1) printf("%d\n",SnakeMatrix[i][j]);
                                    else printf("%d ",SnakeMatrix[i][j]);
                                }
                        }
                }
            count = 1;
        }
    return 0;
}

赞 (0)

Comment