Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3, You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int[][] dir = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
int[] step = new int[]{n,n-1};
int i=0, j=-1;
int d=0;
int num=1;
while(step[d%2]>0){
for(int k=0; k<step[d%2]; k++){
i += dir[d][0];
j += dir[d][1];
ans[i][j] = num++;
}
step[d%2]--;
d = (d+1)%4;
}
return ans;
}
}