保存四个方向向量,将其与当前坐标不断叠加,非法坐标则换一个方向
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int dircount = 0;
    int juzhen[n+1][n+1];
    fill_n(&juzhen[0][0], (n+1) * (n+1), -1);
    int x = 1, y = 1;
    juzhen[x][y] = 1;
    for (int i = 2; i <= n * n; i++)
    {
        int px = x + dir[dircount % 4][0];
        int py = y + dir[dircount % 4][1];
        if (px > 0 && px <= n && py > 0 && py <= n)
        {
            if (juzhen[px][py] == -1)
                juzhen[px][py] = i;
            else
            {
                dircount++;
                px = x + dir[dircount % 4][0];
                py = y + dir[dircount % 4][1];
                juzhen[px][py] = i;
            }
        }
        else
        {
            dircount++;
            px = x + dir[dircount % 4][0];
            py = y + dir[dircount % 4][1];
            juzhen[px][py] = i;
        }
        x = px;
        y = py;
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cout << juzhen[i][j] << " ";
        }
        cout << endl;
    }
}