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 ] ]
//TC=O(n^2)
public class Solution {
public int[][] generateMatrix(int n) {
//special case
if(n==0) return new int[0][0];
int[][] res = new int[n][n];
int num = 1;
int top=0, right=n-1, bottom=n-1, left=0;
while(top<bottom){
//上边框
for(int i=left; i<right; i++){
res[top][i]=num;
num++;
}
//右边框
for(int i=top; i<bottom; i++){
res[i][right]=num;
num++;
}
//下边框
for(int i=right; i>left; i--){
res[bottom][i]=num;
num++;
}
//左边框
for(int i=bottom; i>top; i--){
res[i][left]=num;
num++;
}
//这里容易遗漏
top++;
right--;
bottom--;
left++;
}
//when top=bottom, it comes to the center
if(num==n*n)
res[top][top]=num;
return res;
}
}