二、边界问题

蛇形矩阵

题目描述

输入两个整数

n 和 m,输出一个 n 行 m 列的矩阵,将数字 1 到 n×m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。

输入格式
输入共一行,包含两个整数n和m。

输出格式
输出满足要求的矩阵。 矩阵占 n 行,每行包含m个空格隔开的整数。

样例
输入数据
3 3
输出数据
1 2 3
8 9 4
7 6 5
数据范围
1≤n,m≤100.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int arr[105][105];


int main() {
	int n, m;
	cin >> n >> m;
	int left = 1;
	int  top = 1;
	int bottom = n;
	int right = m;
	int ans = 1;

	while (ans <= n * m) {
		//上排
		int l = left;

		while (l <= right) {

			arr[left][l] = ans;
			ans++;
			l++;
		}

		top++;
		if(top>bottom)
		break;

		//右排
		int t = top;

		while (t <= bottom) {
			arr[t][right] = ans;
			ans++;
			t++;
		}

		right--;
		if(right<left)
		break;


		//下排
		int r = right;

		while (r >= left) {
			arr[bottom][r] = ans;
			ans++;
			r--;
		}

		bottom--;
		if(bottom<top)
		break;

		//左排
		int b = bottom;

		while (b >= top) {
			arr[b][left] = ans;
			ans++;
			b--;
		}

		left++;
		if(left>right)
		break;




	}

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << arr[i][j] << " ";
		}

		cout << endl;
	}





	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值