遇到撞墙的边界情况怎么处理(两种情况)?
1.撞到边界(int d 决定是否要改变方向)
2.已经走过的格子(需要一个标记数组标记是否走过)
d = (d + 1) % 4; // 转变方向
参考代码
#include <iostream>
using namespace std;
const int N = 110;
int n, m;
int res[N][N];
int main()
{
cin >> n >> m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int x = 0, y = 0;
int d = 1; // 一开始向右边走(x, y + 1)
for (int i = 1; i <= n * m; i ++){
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || res[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 ++){
cout << res[i][j] << ' ';
}
cout << endl;
}
return 0;
}