算法的乐趣c/c++ —— 1.1.4入门习题

声明:摘选自“ 算法竞赛入门经典(第2版)”作者:  刘汝佳  /  陈锋   ISBN:9787302291077

蛇形填数。在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<stdio.h>
#include<string.h>
int a[9][9];
int main()
{
	int x, y, n, num;         //x,y用于记录元素坐标,num为数值,坐标系等同于矩阵坐标系 
	scanf("%d", &n);
	memset(a, 0, sizeof(a));  //将矩阵初始化为全0矩阵 
	num = a[x=0][y=n-1] = 1;  //初始化各变量的数值,以及矩阵元素的起始值
	while(num < n*n)          //循环读入所有数值
	{
		while(x+1<n  && !a[x+1][y]) a[++x][y] = ++num;   //走向↓,如果行数没有超过n,并且下一个数是0,循环 
		while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++num;   //走向←,如果行数没有超过n,并且下一个数是0,循环 
		while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++num;   //走向↑,如果行数没有超过n,并且下一个数是0,循环 
		while(y+1<n  && !a[x][y+1]) a[x][++y] = ++num;   //走向→,如果行数没有超过n,并且下一个数是0,循环 
	} 
	for(x=0; x<n; x++)
	{
		for(y = 0; y < n; y++) printf("%3d", a[x][y]);
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lpp5406813053/article/details/84726927