Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]题意:将1...n^2按顺时针方向排列成n * n的矩阵
代码:
public static void fill(int[][] a, int startx, int starty, int endx, int endy, int n)
{
if(startx > endx || starty > endy)
return;
for(int i = starty; i <= endy; i++)
a[startx][i] = n++;
for(int i = startx + 1; i <= endx - 1; i++)
a[i][endy] = n++;
if(endy > starty)
{
for(int i = endy; i >= starty; i--)
a[endx][i] = n++;
}
for(int i = endx - 1; i >= startx + 1; i--)
a[i][starty] = n++;
fill(a, startx + 1, starty + 1, endx - 1, endy - 1, n);
}
public static int[][] generateMatrix(int n)
{
int[][] a = new int[n][n];
fill(a, 0, 0, n - 1, n - 1, 1);
return a;
}