模拟法 出界或已经遍历过就改变方向
#include<bits/stdc++.h>
using namespace std;
const int N = 110;
int g[N][N];
int n, m;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
void bfs(){
int x = 1, y = 1; g[1][1] = 1;
int t = 0;
for(int i = 2; i <= n * m; ++ i){
int a = x + dx[t], b = y + dy[t];
if(a < 1 || a > n || b < 1 || b > m || g[a][b]) {
t = (t + 1) % 4; a = x + dx[t], b = y + dy[t];
}
g[a][b] = i;
x = a, y = b;
}
}
int main(){
cin >> n >> m;
bfs();
for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= m; ++ j){
cout << g[i][j] << ' ';
}
cout << '\n';
}
return 0;
}