https://www.acwing.com/problem/content/3211/
#include<bits/stdc++.h>
using namespace std;
const int N=510;
int dx[]={0,1,1,-1},dy[]={1,-1,0,1};
int n;
int a[N][N];
int main()
{
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
}
}
int count=0;
bool st=false;
int i=0;
int x=1,y=1;
int len=n*n-1;
int flag=1;
printf("%d ",a[1][1]);
while(len--){
i=i%4;
x=x+dx[i],y=y+dy[i];
if(x<=0||y<=0||x>n||y>n){
x=x+dx[(i+1)%4],y=y+dy[(i+1)%4];
}
printf("%d ",a[x][y]);
if(i==1||i==3){
if(flag!=count){
flag++;
continue;
}
}
if(count==n-1)st=true;
if(i==0||i==2){
flag=1;
if(st==false)count++;
else count--;
}
i++;
}
return 0;
}