This topic is a topic that simulates an array. There is no advanced algorithm itself. It mainly examines the ability to describe abstract things with code. According to the boundaries of the array, the upper, left, lower, and right boundaries can be determined, and each for loop fills one. side.
class Solution {
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int up = 0,down = n-1,left = 0,right = n-1,index = 1;
while(index <= n*n){
for(int i = left;i<=right;i++){
array[up][i] = index++;
}
up++;
for(int i = up;i<=down;i++){
array[i][right] = index++;
}
right--;
for(int i = right;i>=left;i--){
array[down][i] = index++;
}
down--;
for(int i = down;i>=up;i--){
array[i][left] = index++;
}
left++;
}
return array;
}
}