首页 > 学院 > 开发设计 > 正文

算法-蛇形数组

2019-11-06 07:02:17
字体:
来源:转载
供稿:网友
/*在n*n方阵里填入1,2,3,..nxn的数,要求埴成蛇形,例如n=4的方阵为10 11 12 19  16 13 28  15 14 37  6  5  4*/int m[maxn][maxn];void SnakeFillNum(){	int n, x, y, tot = 0;	scanf_s("%d", &n);	memset(m, 0, sizeof(a));	tot = m[x = 0][y = n - 1] = 1;	while (tot < n*n)	{		while (x + 1 < n && !m[x + 1][y]) m[++x][y] = ++tot;		while (y - 1 >= 0 && !m[x][y - 1]) m[x][--y] = ++tot;		while (x - 1 >= 0 && !m[x - 1][y])m[--x][y] = ++tot;		while (y + 1 < n && !m[x][y + 1])m[x][++y] = ++tot;	}	for (x = 0; x < n; x++)	{		for (y = 0; y < n; y++)		{			PRintf_s("%3d", m[x][y]);		}		printf_s("/n");	}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表