题目描述
输入两个整数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
写法1
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m; cin >> n >> m;
vector<vector<int> > v(n, vector<int>(m, 0));
int left = 0, right = m - 1, up = 0, down = n - 1, cur = 1;
while (true) {
for (int i = left; i <= right; i ++ ) v[up][i] = cur ++ ;
up ++ ;
if (up > down) break;
for (int i = up; i <= down; i ++ ) v[i][right] = cur ++ ;
right -- ;
if (left > right) break;
for (int i = right; i >= left; i -- ) v[down][i] = cur ++ ;
down -- ;
if (up > down) break;
for (int i = down; i >= up; i --) v[i][left] = cur ++ ;
left ++ ;
if (left > right) break;
}
for (int i = 0; i < n; i ++ ) {
for (int j = 0; j < m; j ++ )
cout << v[i][j] << ' ';
cout << endl;
}
return 0;
}
写法2
#include <iostream>
using namespace std;
const int N = 110;
int ret[N][N], n, m;
// 这里的方向一定要按照 右->下->左->上 的顺序写
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int main() {
cin >> n >> m;
for (int i = 0, j = 0, k = 1, d = 0; k <= n * m; k ++ ) {
ret[i][j] = k;
int a = i + dx[d], b = j + dy[d];
// 出界或者该位置已经有值了
if (a < 0 || b < 0 || a >= n || b >= m || ret[a][b]) {
d = (d + 1) % 4;
a = i + dx[d], b = j + dy[d];
}
i = a, j = b;
}
for (int i = 0; i < n; i ++ ) {
for (int j = 0; j < m; j ++ )
cout << ret[i][j] << ' ';
cout << endl;
}
return 0;
}