蛇形填数(小模拟训练)

解题思路:带着练的一道小模拟题,实际就是控制x,y坐标按照固定的规律变化。可以将问题分成四段,开始从右上角向下向下,然后向左向左,向上向上,向右向右,如此循环往复,跳出状态的条件为前进方向已经被赋值或走到了边缘,以下是核心代码:

while(total<n*n)
	{
		while(x+1<=n&&!graph[x+1][y]) graph[++x][y]=++total;       //向下向下,遇到已经赋值的元素或走到边缘即跳出状态 
		while(y-1>=1&&!graph[x][y-1]) graph[x][--y]=++total;
		while(x-1>=1&&!graph[x-1][y]) graph[--x][y]=++total;
		while(y+1<=n&&!graph[x][y+1]) graph[x][++y]=++total;
	}

描述 在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<stdio.h>
#include<string.h>
int graph[51][51];
int main()
{
	int n;
	scanf("%d",&n);
	memset(graph,0,sizeof(graph));
	int x,y,total=0;
	graph[x=1][y=n]=++total;
	while(total<n*n)
	{
		while(x+1<=n&&!graph[x+1][y]) graph[++x][y]=++total;       //向下向下,遇到已经赋值的元素或走到边缘即跳出状态 
		while(y-1>=1&&!graph[x][y-1]) graph[x][--y]=++total;
		while(x-1>=1&&!graph[x-1][y]) graph[--x][y]=++total;
		while(y+1<=n&&!graph[x][y+1]) graph[x][++y]=++total;
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			printf("%d ",graph[i][j]);
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mavises/article/details/81510982
今日推荐