左开右闭
class Solution {
public int[][] generateMatrix(int n) {
int startX = 0;
int startY = 0;
int count = 1;
int offset = 1;
int nums[][] = new int[n][n];
int loop = n/2;
while (loop > 0) {
int j = startY;
int i = startX;
for(j = startY;j<n-offset;j++){
nums[startX][j] = count;
count++;
}
for(i = startX; i < n - offset; i++){
nums[i][j] = count;
count++;
}
for(;j>offset-1;j--){
nums[i][j] = count++;
}
for(;i>offset-1;i--){
nums[i][startY] = count++;
}
offset++;
startX++;
startY++;
loop--;
}
int mid = n/2;
if(n%2!=0){
nums[mid][mid] = count;
}
return nums;
}
}
关键是找到不变量,要清楚认识到每一行每一列的总变量是什么。