定一个正整数n,输出如下 n  n “之字形”方阵。

定一个正整数n,输出如下 n  n “之字形”方阵。

例: 8  8 方阵。

例子

C语言实现

#include<stdio.h>
#define x 100
int main(void)
{
	int n,i=0,j=0,m=1;
	scanf_s("%d", &n);//输入多少行
	int a[x][x] = {1};
	while (1)
	{
			if (m < (n * (n - 1) / 2 )+ n)
			{
				j++;
			}
			else
			{
				i++;
			}
			m++;
			if (m > n * n)
				break;
			a[i][j] = m;
			do {
				i++;
				j--;
				m++;
				if (m > n * n)
					break;
				a[i][j] = m;
				if (m <=(n * (n-1) / 2) + n)
				{
					if (j == 0)
						break;
				}
				else
				{
					if (i == n-1) 
						break;
				}
			} while (1);
			if (m < (n * (n - 1) / 2 )+ n)
			{
				i++;
			}
			else
			{
				j++;
			}
			m++;
			if (m > n * n)
				break;
			a[i][j] = m;
			do {
				i--;
				j++;
				m++;
				if (m > n * n)
					break;
				a[i][j] = m;
				if (m <=(n * (n - 1) / 2) + n)
				{
					if (i == 0)
						break;
				}
				else
				{
					if (j == n-1) 
						break;
				}
			} while (1);
	}
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
			printf("%d\t", a[i][j]);
		printf("\n");
	}
	return 0;
}

在这里插入图片描述

回型方阵是一种特殊的方阵,其元素按照回字形排列。给定一个正整数n,我们需要输出一个n×n的回型方阵。 思路: 1. 首先我们可以创建一个n×n的二维数组matrix,并初始化每个元素为0。 2. 义四个变量top、bottom、left、right,分别表示当前方阵的上边界、下边界、左边界和右边界。 3. 一个计数器count,初始值为1。表示将要填充的下一个数字。 4. 使用一个while循环进行填充操作,判断条件为left <= right and top <= bottom。 5. 从左到右填充top行,即将count从left到right依次赋值给matrix[top][i],同时count加一。 6. 当top行填充完后,将top加一,表示上边界已经向下移动一行。 7. 接着从上到下填充right列,即将count从top到bottom依次赋值给matrix[i][right],同时count加一。 8. 当right列填充完后,将right减一,表示右边界已经向左移动一列。 9. 继续从右到左填充bottom行,即将count从right到left依次赋值给matrix[bottom][i],同时count加一。 10. 当bottom行填充完后,将bottom减一,表示下边界已经向上移动一行。 11. 最后从下到上填充left列,即将count从bottom到top依次赋值给matrix[i][left],同时count加一。 12. 当left列填充完后,将left加一,表示左边界已经向右移动一列。 13. 当while循环结束后,即每个位置都被正确填充了之后,我们输出matrix即可。 下面是具体的代码实现: ```python def generateMatrix(n): matrix = [[0] * n for _ in range(n)] top, bottom, left, right = 0, n - 1, 0, n - 1 count = 1 while left <= right and top <= bottom: for i in range(left, right + 1): matrix[top][i] = count count += 1 top += 1 for i in range(top, bottom + 1): matrix[i][right] = count count += 1 right -= 1 for i in range(right, left - 1, -1): matrix[bottom][i] = count count += 1 bottom -= 1 for i in range(bottom, top - 1, -1): matrix[i][left] = count count += 1 left += 1 return matrix n = 5 matrix = generateMatrix(n) for row in matrix: print(row) ``` 以上代码会输出一个5×5的回型方阵: ``` [1, 1, 1, 1, 1] [2, 0, 0, 0, 1] [2, 0, 0, 0, 1] [2, 0, 0, 0, 1] [2, 2, 2, 2, 2] ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值