NYOJ033蛇形填数

n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4

输入

直接输入方的维数,即n的值。(n<=100)

输出

输出结果是蛇形方

样例输入

3

样例输出

7 8 1

6 9 2

5 4 3

                        这里我为了好看对格式做了处理,并改成了多组输入,提交肯不过呀

#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
    int n;
    int a[101][101];
    while(cin>>n)
    {
        int M=0,N=n-1;  //在主对角线左上和右下设立标志
        int x; //行坐标
        int y; //列坐标
        int i=1,j;
        while(i<n*n-1)
        {
            for(x=M,y=N; x<=N; x++)
            {
                a[x][y]=i++;
            }
            x--;
            N--; //右下方标志向左上趋近一位
            for(y=N; y>=M; y--)
            {
                a[x][y]=i++;
            }
            y++;
            for(x=N; x>=M; x--)
            {
                a[x][y]=i++;
            }
            x++;
            M++; //左上方标志向右下趋近一位
            for(y=M; y<=N; y++)
            {
                a[x][y]=i++;
            }
            y--;
        }
        if(n%2)
            a[M][N]=i;

        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
                cout<<setiosflags(ios::right)<<setw(3)<<a[i][j]<<" ";
            cout<<endl;
        }

    }



    return 0;
}

更新,看了别人的代码,感觉自己的好乱

下面是根据别人代码改进的

#include <iostream>

using namespace std;


int main()
{
    int n;
    int a[101][101];
    while(cin>>n)
    {
        int circle=0;
        int k=1;
        int i=0;
        int j=n-1;
        while(k<=n*n)
        {
            for (; i<n-circle; i++)
            {
                a[i][j]=k++;
            }
            i--;
            for (j-=1; j>=circle; j--)
            {
                a[i][j]=k++;
            }
            j++;
            for (i-=1; i>=circle; i--)
            {
                a[i][j]=k++;
            }
            i++;
            circle++;
            for (j+=1; j<n-circle; j++)
            {
                a[i][j]=k++;
            }
            j--;
            i++;

        }


        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
            {
                cout<<a[i][j]<<" ";
            }
            cout<<endl;

        }


    }

    return 0;
}



原文地址:https://www.cnblogs.com/zhanyeye/p/9746125.html