算法
(暴力枚举) $O(n^2)$
参考了y总 Acwing 756.蛇形矩阵的做法, 一圈一圈地循环
C++ 代码
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110;
int q[N][N];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int main()
{
int n;
while (cin >> n, n)
{
memset(q, 0, sizeof q);
int x = 0, y = 0, dir = 1, turn = 0, cur = 1; //turn记录了变向的次数
for (int i = 1; i <= n * n; i++)
{
q[x][y] = cur;
int a = x + dx[dir], b = y + dy[dir];
if (a < 0 || a >= n || b < 0 || b >= n || q[a][b])
{
dir = (dir + 1) % 4;
a = x + dx[dir], b = y + dy[dir];
turn ++;
if (turn != 0 && turn % 4 == 0) cur ++;
}
x = a, y = b;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << q[i][j] << ' ';
cout << endl;
}
cout << endl;
}
}