class spiral
{
public static void main(String args[])
{
int rowLimit = 3;
int colLimit = 3;
int source[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
/*int rowLimit = 4;
int source[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}};*/
int[][] remap = new int[rowLimit+1][colLimit+1];
for (int i = 0; i <= rowLimit; i++)
{
for (int j = 0; j <= colLimit; j++)
{
remap[i][j] = 99;
}
}
int urow = rowLimit;
int ucol = colLimit;
int lrow = 1;
int lcol = 0;
int colIndex = -1;
int rowIndex = 0;
int a = 0; //across
int b = 1; //back
int u = 2; //up
int d = 3; //down
int udba = a;
for (int i = 0; i <= rowLimit;i++)
{
for (int j = 0; j <= colLimit;j++)
{
if (udba == a)
{
if (colIndex == ucol-1)
{
udba = d;
ucol--;
}
colIndex++;
}
else if (udba == d)
{
if (rowIndex == urow-1)
{
udba = b;
urow--;
}
rowIndex++;
}
else if (udba == b)
{
if (colIndex == lcol+1)
{
udba = u;
lcol++;
}
colIndex--;
}
else if (udba == u)
{
if (rowIndex == lrow+1)
{
udba = a;
lrow++;
}
rowIndex--;
}
//System.out.println("row = "+i+"|col = "+j+"|rowIndex = "+rowIndex+"|colIndex = "+colIndex+"|/n");
if (rowIndex >= 0 && rowIndex <= rowLimit && colIndex >= 0 && colIndex <= colLimit)
remap[rowIndex][colIndex] = source[i][j];
}
}
for (int i = 0; i<= rowLimit;i++)
{
String output = "";
for (int j = 0; j<= colLimit;j++)
{
if (j == 0)
output = output = output + remap[i][j];
else
output = output = output + "," + remap[i][j];
}
System.out.println(output);
}
}
}