蛇形填数

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=7

先把外围填好再考虑深入循环。递归没成功,就用了循环。这段代码虽然解决了问题,但是并不好。

#include <stdio.h>
void Full(int a[][101], int n,int count)
{
	int i,j,t,temp;                                        //temp记录深入程度
	t = n*n;                                               //记录最大数
	for(i = 1, j = n, temp = 1; count <= t; i++,temp++)
	{
		while(i <= j)										//右边一列 
		{
			if(count == t)									//奇数情况
			{
				a[i][j] = count;
				return;
			}
			a[i][j] = count;
			i++;
			count++;
		}
		i--;count--;
		while(j >= temp)									//下边一列
		{
			a[i][j] = count;
			j--;
			count++;
		}
		j++;count--;
		while(i >= temp)									//左边一列
		{
			a[i][j] = count;
			i--;
			count++;
		}
		i++;count--;
		while(j <= n-temp)									//上边一列
		{
			a[i][j] = count;
			j++;
			count++;
		}
		j--;		
	}

}
int main()
{
	int a[101][101] = {0};
	int i,j,n;

	scanf("%d",&n);
	Full(a,n,1);

	for(i = 1; i <= n; i++ )
	{
		for(j = 1; j <= n; j++)
		{
			printf("%d ",a[i][j]);
		}
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(蛇形填数)