思路:顺时针,逐层填数
#include <iostream>
using namespace std;
int a[1001][1001];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, x = 1, y = 1, z = 2;
cin >> n >> m;
a[x][y] = 1;
while (z <= n * m) {
while (y + 1 <= m && a[x][y + 1] == 0) a[x][++y] = z++;//等于零是为了不重复遍历,
while (x + 1 <= n && a[x + 1][y] == 0) a[++x][y] = z++;
while (y - 1 >= 1 && a[x][y - 1] == 0) a[x][--y] = z++;
while (x - 1 >= 1 && a[x - 1][y] == 0) a[--x][y] = z++;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j != 1) cout << " ";
cout << a[i][j];
}
cout << "\n";
}
return 0;
}