Guo Qiang

蛇形填数问题

发布日期 2020-11-07 19:53:10已读 625 次CODE
image

在 n*n 的方阵里填入 1,2,...,n*n,要求填成蛇形。


#include <stdio.h>

#define MAX 10

int a[MAX][MAX] = {0};

int main()
{
	int i, j, n = 0;
	n = a[i = 0][j = MAX - 1] = 1;

	while (n < MAX * MAX) {
		while (i+1<MAX && !a[i+1][j]) a[++i][j] = ++n;
		while (j-1>=0 && !a[i][j-1])  a[i][--j] = ++n;
		while (i-1>=0 && !a[i-1][j])  a[--i][j] = ++n;
		while (j+1<MAX && !a[i][j+1]) a[i][++j] = ++n;
	}

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

	return 0;
}


Copyright © 2019~2024 Guo Qiang
Pages viewed 31,263,767