n=4
output:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
public class Main {
public static void main(String[] args) {
snakeWrite(4);
}
public static void snakeWrite(int n)
{
int[][] a=new int[n][n];
int x,y;
int value=a[x=0][y=n-1]=1;
while(value<n*n)
{
while(x+1<n&&a[x+1][y]==0) a[++x][y]=++value;
while(y-1>=0&&a[x][y-1]==0) a[x][--y]=++value;
while(x-1>=0&&a[x-1][y]==0) a[--x][y]=++value;
while(y+1<n&&a[x][y+1]==0) a[x][++y]=++value;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.printf("%3d",a[i][j]);
}
System.out.println();
}
}
}