756. 蛇形矩阵
输入两个整数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
通过定义 上,下,左,右四个变量模拟螺旋过程
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int N = 110;
int n,m;
int g[N][N];
int main() {
cin >> n >> m;
int k=1;
int left = 0, right = m-1, top = 0, bottom = n-1;
while(true) {
for(int j = left; j <= right; j++) g[top][j] = k++;
if(++top > bottom) break;
for(int j = top; j <= bottom; j++) g[j][right] = k++;
if(--right < left) break;
for(int j = right; j >= left; j--) g[bottom][j] = k++;
if(--bottom < top) break;
for(int j = bottom; j >= top; j--) g[j][left] = k++;
if(++left > right) break;
}
for(int i = 0; i < n; i++) {
cout << g[i][0];
for(int j = 1; j < m; j++) {
cout << ' ' << g[i][j];
}
cout << '\n';
}
return 0;
}