先创建一个二维数组,以及两个分别控制x轴和y轴的数组,放入for循环,当数组中的数到边界,执行对应的上下左右的操作使其满足蛇形数组
此题比较复杂不好解释
AC代码如下
#include <iostream>
#include <algorithm>
using namespace std;
int n, m;
int a[101][101];
bool st[101][101] = { false };
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
int d = 1, x = 0, y = 0;
int main()
{
cin >> n >> m;
for (int i = 1; i <= n * m; i++)
{
a[x][y] = i;
st[x][y] = true;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || st[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 << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
return 0;
}