慕课第九周_蛇形矩阵

程序运行结果示例1:

Input n:

5↙

1 2 6 7 15

3 5 8 14 16

4 9 13 17 22

10 12 18 21 23

11 19 20 24 25

程序运行结果示例2:

Input n:

4↙

扫描二维码关注公众号,回复: 4753975 查看本文章

1 2 6 7

3 5 8 13

4 9 12 14

10 11 15 16

#include <stdio.h>
#define N 10
void ZigzagMatrix(int a[N][N],int n);
int main()
{
	int a[N][N],n;
	printf("Input n:\n");
	scanf("%d",&n);
	if(n>0 && n<100)
	{
		ZigzagMatrix(a,n);	
	}
	else
	{
		printf("Input error!\n");
	}
	return 0;
}
void ZigzagMatrix(int a[][N],int n)
{
	int hang,lie,round;
    int count = 1;
    if(1 == n)
    {
        a[0][0] = count;
    }
    else
    {
        for(round = 1;round <= n;round++)
        {
			if(round%2==0)//偶数圈数列向斜上方递增
			{
				for(lie = 0;lie < round;lie++)
				{
					a[round - 1 - lie][lie] = count;
					count++;
				}
			}
			else//奇数圈数列向斜下方递增
			{
					for(lie = 0;lie < round;lie++)
				{
					a[lie][round - 1 - lie] = count;
					count++;
				}
			}

        }
 
        for(;round <= 2 * n - 1;round++)
        {
			if(round%2==0)
			{
				for(lie = round - n;lie < n;lie++)
				{
					a[round - 1 - lie][lie] = count;
					count++;
				}
			}
			else
			{
				for(lie = round - n;lie < n;lie++)
				{
					a[lie][round - 1 - lie] = count;
					count++;
				}
			}

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

猜你喜欢

转载自blog.csdn.net/weixin_43759910/article/details/85166485