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

代码:

#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循环始终控制的是矩阵最右端的一列。
同理,第三个循环控制最下端的一行,第四个循环控制最左端的一列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值