alt

#include<stdio.h>

int main()
{
    int arr[20][20] = { 0 };
    int n = 0, m = 1;
    int i = 0,j = 0,flag=0;
    scanf("%d", &n);
    //思路大概是先往右上旋,然后往左下旋,再往右上旋,如此往复
    //当其碰到边界时,停止移动
    while (m <= n * n)
    {
        //右上旋
        while (i >= 0&& (m <= n * n)&&j<=n-1)
        {
            arr[i][j] = m++;
            i--;
            j++;
        }
        flag++;
        if (flag < n)
            i++;
        else if (flag == n)
        {
            i += 2;
            j--;
        }
        else
        {
            i+=2;
            j--;
        }
        //左下旋
        while (j >= 0 && (m <= n * n)&&i<=n-1)
        {
            arr[i][j] = m++;
            i++;
            j--;
        }
        flag++;
        if (flag < n)
            j++;
        else if(flag==n)
        {
            j += 2;
            i--;
        }
        else
        {
            i--;
            j+=2;
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }
    return 0;
}