代码:
class Solution {
public int[][] generateMatrix(int n) {
if(n==1){
int[][] arr = {{1}};
return arr;
}
int[][] arr = new int[n][n];
int cnt=1;
int left = 0,right = n-1,top=0,down=n-1;
while(left<right){
for(int i=left;i<right;i++){
arr[top][i] = cnt++;
}
for(int j=top;j<down;j++){
arr[j][right] = cnt++;
}
for(int i=right;i>left;i--){
arr[down][i] = cnt++;
}
for(int j=down;j>top;j--){
arr[j][left] = cnt++;
}
left++;
right--;
top++;
down--;
}
if(cnt==n*n){
arr[left][top] = n*n;
}
return arr;
}
}