当前位置 博文首页 > 一位初中编程爱好者的博客:2045:【例5.13】蛇形填数

    一位初中编程爱好者的博客:2045:【例5.13】蛇形填数

    作者:[db:作者] 时间:2021-08-29 22:29

    题目

    2045:【例5.13】蛇形填数

    时间限制: 1000 ms 内存限制: 65536 KB
    提交数: 1201 通过数: 626
    【题目描述】
    在n×n方阵里填入1,2,3,…,n×n,要求填成蛇形。例如n=4时方阵为:

    10 11 12 1
    9 16 13 2
    8 15 14 3
    7 6 5 4
    其中,n≤20。

    【输入】
    输入n。

    【输出】
    输出题述方阵。n行,每行各数之间用一个空格隔开。

    【输入样例】
    4
    【输出样例】
    10 11 12 1
    9 16 13 2
    8 15 14 3
    7 6 5 4


    题目分析:要想直接求出某个坐标对应的数据很困难,但我们可以把方阵分成多层,先填最外面的一层,然后填第二层……直到把方阵填满。假如原来的方阵边长为n,则填上最外一层后就变成一个边长(n-2)的方阵。通过方阵边长,我们就可以求出最外层的数据。


    C++代码

    #include<iostream>
    using namespace std;
    int main()
    {
    	int a[20][20],n;
    	cin>>n;
    	int c=n,temp=1;//c:当前矩阵边长;temp:当前数字
    	while(c)
    	{
    		if(c==1)//只有一个格
    		{
    			a[n/2][n/2]=temp;
    			break;
    		}
    		int y=(n-c)/2,x=(n-c)/2+c-1;
    		int end=y+c-1;
    		for(;y<=end;y++,temp++)//处理右面
    		{
    			a[y][x]=temp;
    		}
    		y=end;
    		end=x-c+1;
    		x--;
    		for(;x>=end;x--,temp++)//处理下面
    		{
    			a[y][x]=temp;
    		}
    		x=end;
    		end=y-c+1;
    		y--;
    		for(;y>=end;y--,temp++)//处理左面
    		{
    			a[y][x]=temp;
    		}
    		y=end;
    		end=x+c-1;
    		x++;
    		for(;x<end;x++,temp++)//处理上面
    		{
    			a[y][x]=temp;
    		}
    		c-=2;//矩阵边长缩小2
    	}
    	for(int i=0;i<n;i++)
    	{
    		for(int j=0;j<n;j++)
    		{
    			cout<<a[i][j]<<' ';
    		}
    		cout<<endl;
    	}
    }
    

    运行结果

    5*5蛇形方阵

    cs