AcWing 756.蛇形矩阵(模拟法)

这段代码实现了一个填充蛇形矩阵的算法,从左上角开始,按顺时针方向填充值。矩阵的形状根据输入的行数n和列数m动态调整。程序首先初始化矩阵,然后通过四个嵌套循环按蛇形路径填充数值,最后输出填充后的矩阵。这个算法适用于需要创建类似棋盘风格排列的数据结构问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main() {
	int m,n;
	int left=0,top=0;
	cin>>n>>m;
	int right=m-1,bottom=n-1;
	int k=1;
	while(left<=right||top<=bottom) {
		for(int i=left; i<=right&&top<=bottom; i++) {
			a[top][i]=k++;
		}
		top++;
		for(int i=top; i<=bottom&&left<=right; i++) {
			a[i][right]=k++;
		}
		right--;
		for(int i=right; i>=left&&top<=bottom; i--) {
			a[bottom][i]=k++;
		}
		bottom--;
		for(int i=bottom; i>=top&&left<=right; i--) {
			a[i][left]=k++;
		}
		left++;
	}
	for(int i=0; i<n; i++) {
		for(int j=0; j<m; j++) {
			cout<<a[i][j];
			if(j!=m-1)
				cout<<" ";
		}
		if(i!=n-1)
			cout<<endl;
	}
	return 0;
}

分析:
从题目描述中可以分析出,蛇形矩阵就是从矩阵的左上角->右上角->右下角->左下角的一个由外向内的循环。那么我们就可以通过模拟这样的过程给数组赋值,从而得到我们想要的结果并输出。

代码段落分析:

while(left<=right||top<=bottom) {
		for(int i=left; i<=right&&top<=bottom; i++) {
			a[top][i]=k++;
		}
		top++;
		for(int i=top; i<=bottom&&left<=right; i++) {
			a[i][right]=k++;
		}
		right--;
		for(int i=right; i>=left&&top<=bottom; i--) {
			a[bottom][i]=k++;
		}
		bottom--;
		for(int i=bottom; i>=top&&left<=right; i--) {
			a[i][left]=k++;
		}
		left++;
	}

第一个for循环,i控制列从left->right,并且行top始终不变,可以将数组从第top行的第left个遍历到第right个。而循环条件可以保证在整个while循环中,这一个for循环始终控制的是矩阵最上端的一行。

第二个for循环,i控制行从top->bottom,并且列right始终不变,可以将数组从第right列的第top个遍历到第bottom个。循环条件可以保证在整个while循环中,这一个for循环始终控制的是矩阵最右端的一列。
同理,第三个循环控制最下端的一行,第四个循环控制最左端的一列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值