vector<vector<int>> generateMatrix(int n)
时间: 2023-12-16 08:06:18 浏览: 150
Vector_matrix
可以的,这是一个生成n阶矩阵的函数,你可以参考下面的代码实现:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int top = 0, right = n-1, bottom = n-1, left = 0;
int num = 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
res[top][i] = num++;
}
top++;
for (int i = top; i <= bottom; i++) {
res[i][right] = num++;
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
res[bottom][i] = num++;
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
res[i][left] = num++;
}
left++;
}
}
return res;
}
希望能帮到你!
阅读全文