输入两个整数 n 和 m,输出一个 n 行 m 列的矩阵,将数字 1 到 n×m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
输入格式
输入共一行,包含两个整数 n 和 m。
输出格式
输出满足要求的矩阵。
矩阵占 n 行,每行包含 m 个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
原题连接:
https://www.acwing.com/problem/content/758/
// 太优雅了,简直太优雅了。。
// 利用left, right, top, bottom四个变量,来表示矩形的四个边界
// 抽象成每次循环处理一个环
#include<iostream>
using namespace std;
const int N = 105;
int a[N][N];
int n, m;
int main()
{
cin >> n >> m;
int left = 0, right = m - 1, top = 0, bottom = n - 1;
int k = 1;
while(left <= right && top <= bottom)
{
// 处理上部
for(int i = left; i <= right; i ++)
a[top][i] = k ++;
// 处理右部
for(int i = top + 1; i <= bottom; i ++)
a[i][right] = k ++;
// 处理下部,有可能没有下部,所以要多个条件top < bottom
for(int i = right - 1; i >= left && top < bottom; i --)
a[bottom][i] = k ++;
// 处理左部分,有可能没有左部
for(int i = bottom - 1; i > top && left < right; i --)
a[i][left] = k ++;
left ++, right --, top ++, bottom --;
}
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < m; j ++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}