C++ 代码
#include<cstdio>
int q[110][110] ={0};
int main(){
int dx[] ={0,1,0,-1},dy[] = {1,0,-1,0};
int N,M;
scanf("%d%d",&N,&M);
int x =0,y=0,d =0;
for(int i =1;i<=N*M;i++){
q[x][y] = i;
int a = x+dx[d],b = y+dy[d]; //a用来暂时测试是否到达边界
if(a>=N || b>=M || a<0 || b<0 || q[a][b]){
d = (d+1)%4;
a = x+dx[d],b = y+dy[d];
}
x = a;
y =b;
}
for(int i =0 ;i<N;i++){
for(int j =0;j<M;j++){
printf("%d ",q[i][j]);
}
printf("\n");
}
return 0;
}