本题为模拟矩阵赋值,将赋值的过程看作一圈一圈的赋值过程,每一次分别模拟从左到右,从上到下,从右到左,从下到上的过程,代码如下:
class Solution {
public int[][] generateMatrix(int n) {
int low = 0,high = n-1;//模拟一圈中的左右边界和上下边界
int number = 1;//每次要填入的数字
int[][] result = new int[n][n];
while(low <= high){
for(int j = low;j <= high;j++){//模拟从左到右
result[low][j] = number++;
}
for(int j = low + 1;j <= high;j++){//模拟从上到下
result[j][high] = number++;
}
for(int j = high - 1;j >= low;j--){//模拟从右到左
result[high][j] = number++;
}
for(int j = high - 1;j >= low + 1;j--){//模拟从下到上
result[j][low] = number++;
}
low++;
high--;
}
return result;
}
}