Z字编排 C语言

以 8 * 8 的矩阵为例,坐标每次增减一个单位,规律如下

1. x to 1

     y to 0

2. x to 0

     y to 1

3. x to 2

     y to 0

4. x to 0

     y to 2

....

当 x 或 y 达到 7(上限)后,这个规律发生变化

1. x to 0

     y to 7

2. x to 7

     y to 0

3. x to 1

     y to 7

4. x to 7

     y to 1

....

我们可以从整个Z字编排的路线图中发现,这是一个中心对称的编排。

因此我们只需要Max^2一半的循环次数来解决这个问题(Max为奇数时多一次),选用前面的或是后面的规律构造一个循环,实现坐标从左上角或右下角变化到中间。

以下是我的实现方式

#include <stdio.h>

#define Max 8
#define Mid Max * Max / 2 + Max % 2

int main (int argc, char** argv)
{
	unsigned isX = 0;
	int t = 0, i = 0, d = Max * Max, rect[2] = {0, 0};
	char s[Max][Max];

	while (d != Mid)
	{
		if (rect[isX] < i)
			rect[isX]++;
		if (rect[!isX] > 0)
			rect[!isX]--;

		if (rect[isX] == i)
		{
			i++;
			isX = !isX;
		}

		s[rect[0]][rect[1]] = t++;
		s[Max - 1 - rect[0]][Max - 1 - rect[1]] = --d;
	}

	for (t = 0; t < Max; t++)
	{
		for (i = 0; i < Max; i++)
			printf ("%d\t", s[t][i]);
		printf ("\n");
	}
        return 0;
}
发布了4 篇原创文章 · 获赞 1 · 访问量 3540

猜你喜欢

转载自blog.csdn.net/qq_29791013/article/details/89051732