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 ] ]
按螺旋顺序写
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int beginX=0,beginY=0;
int endX=n-1,endY=n-1;
int temp = 1;
int top=n*n;
while(true){
if(temp>top)
break;
for(int i=beginX;i<=endX;i++)
res[beginY][i]=temp++;
beginY++;
for(int i=beginY;i<=endY;i++)
res[i][endX]=temp++;
endX--;
for(int i=endX;i>=beginX;i--)
res[endY][i]=temp++;
endY--;
for(int i=endY;i>=beginY;i--)
res[i][beginX]=temp++;
beginX++;
}
return res;
}
}