第4讲2*
#include <iostream>
using namespace std;
int res[100][100];
int main()
{
int n, m;
cin >> n >> m;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};//走的方向 /→:(0,1) dx[0]dy[0] ↓:(1,0) dx[1]dy[1] ←:(0,-1) dx[2]dy[2] ↑:(-1,0) dx[3]dy[3] /→(又回到右)
for(int x = 0, y = 0, d = 0, k = 1; k <= n*m; k++) //k是填入的数字从1到n*m
{
res[x][y] = k;
int a = x + dx[d], b = y + dy[d]; //移动
if(a < 0 || a >= n || b < 0 || b >= m || res[a][b])//撞墙:出界(a<0 a>=n b<0 b>=m) 或重复(res[a][b]!=0)
{
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++) cout << res[i][j] << ' ';
cout << endl;
}
return 0;
}