码迷,mamicode.com
首页 > 其他好文 > 详细

蛇形填数

时间:2017-01-11 22:13:52      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:out   语句   memset   ...   size   stream   return   ++   while   

在n×n方阵里填入1,2,...,n×n,要求填成蛇形。例如,n=4时方阵为:

10  11  12  1

 9   16  13  2

 8   15  14  3

 7    6    5   4

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define max 100
int aa[max][max];
int main()
{
    int n;
    while(cin>>n)
    {
        int x,y;
        memset(aa,0,sizeof(aa));
        int tot=aa[x=0][y=n-1]=1;
        while(tot<n*n)
        {
            //四条while语句都是先判断,再移动
            while(x+1<n&&!aa[x+1][y])
                aa[++x][y]=++tot;
            while(y-1>=0&&!aa[x][y-1])
                aa[x][--y]=++tot;
            while(x-1>=0&&!aa[x-1][y])
                aa[--x][y]=++tot;
            while(y+1<n&&!aa[x][y+1])
                aa[x][++y]=++tot;
        }
        for(int i=0;i<n;i++)
            {
                for(int j=0;j<n;j++)
                printf("%3d",aa[i][j]);
                cout<<endl;
            }
    }
    return 0;
}

蛇形填数

标签:out   语句   memset   ...   size   stream   return   ++   while   

原文地址:http://www.cnblogs.com/Aftersoon-sun/p/6274178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!