【正经题解】回形取数
2024-03-15 11:19:05
发布于:浙江
8阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
int a[1001][1001], cnt = 0;
// 初始化数字矩阵
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] = ++cnt;
}
}
// 回形搜索
int x = 1, y = 1;
cout << a[x][y];
a[x][y] = 0;
for (int i = 2; i <= n * m; i++) {
// 1往下
while (x + 1 <= n and a[x + 1][y] != 0) {
cout << "," << a[++x][y];
a[x][y] = 0;
}
// 2往右
while (y + 1 <= m and a[x][y + 1] != 0) {
cout << "," << a[x][++y];
a[x][y] = 0;
}
// 3往上
while (x - 1 >= 1 and a[x - 1][y] != 0) {
cout << "," << a[--x][y];
a[x][y] = 0;
}
// 4往左
while (y - 1 >= 1 and a[x][y - 1] != 0) {
cout << "," << a[x][--y];
a[x][y] = 0;
}
}
return 0;
}
这里空空如也
有帮助,赞一个