模拟,注意跳出条件
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n));
int u = 0;
int l = 0;
int d = n - 1;
int r = n - 1;
while(true){
bool judge = true;
if(l <= r && u <= d ){
for(int j = l; j <= r; j++){
if(u == 0 && j == 0) ans[u][j] = 1;
else ans[u][j] = ans[u][j - 1] + 1;
judge = false;
}
u++;
}
if(u <= d && l <= r){
for(int j = u; j <= d; j++){
ans[j][r] = ans[j - 1][r] + 1;
judge = false;
}
r--;
}
if(u <= d && l <= r){
for(int j = r; j >= l; j--){
ans[d][j] = ans[d][j + 1] + 1;
judge = false;
}
d--;
}
if(u <= d && l <= r){
for(int j = d; j >= u; j--){
ans[j][l] = ans[j + 1][l] + 1;
judge = false;
}
l++;
}
if(judge) break;
}
return ans;
}
};