蛇形填数

之前因为家里的原因,回乡下一个星期,期间都没有机会,也没有心情写代码,一个星期就这么毫无长进,罪过。

看到一个蛇形填数的题目,搞了搞,代码如下

#include <stdio.h>
#include <stdlib.h>

void print(int **a, int n)
{
	for (int y=0; y<n; y++)
	{
		for (int x=0; x<n; x++)
		{
			printf("%dt", a[x][y]);
		}
		printf("n");
	}
	printf("n");
}

void clear(int **a, int n)
{
	for (int y=0; y<n; y++)
	{
		for (int x=0; x<n; x++)
		{
			a[x][y] = 0;
		}
	}
}

void fill(int **a, int n)
{
	int xx[4] = {1, 0, -1, 0};
	int yy[4] = {0, 1, 0, -1};
	int x=0, y=0, pos=0;
	for (int i=1; i<=n*n; i++)
	{
		a[x][y] = i;
		if (x+xx[pos]>=n || x+xx[pos]<0
			|| y+yy[pos]>=n || y+yy[pos]<0
			|| a[x+xx[pos]][y+yy[pos]]!=0)
		{
			pos = (pos+1) % 4;
		}
		x += xx[pos];
		y += yy[pos];
	}
}

int main()
{
	int n;
	while (scanf("%d", &n) != EOF)
	{

		int **a = (int **)malloc(sizeof(int *) * n);
		for (int i=0; i<n; i++)
		{
			a[i] = (int *)malloc(sizeof(int) * n);
		}
		clear(a, n);
		fill(a, n);
		print(a, n);
		for (int i=0; i<n; i++)
		{
			free(a[i]);
		}
		free(a);
	}
	return 0;
}

输入输出

2
1       2
4       3

5
1       2       3       4       5
16      17      18      19      6
15      24      25      20      7
14      23      22      21      8
13      12      11      10      9

Leave a Reply

Your email address will not be published. Required fields are marked *