文章
19
粉丝
69
获赞
30
访问
18.1k
#include <bits/stdc++.h>
using namespace std;
void generateSpiralMatrix(int n)
{
vector<vector<int>> matrix(n, vector<int>(n, 0));
int num = 1;
int rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1;
while (rowStart <= rowEnd && colStart <= colEnd)
{
// 向下填充
for (int i = rowStart; i <= rowEnd; i++)
{
matrix[i][colStart] = num++;
}
colStart++;
// 向右填充
for (int i = colStart; i <= colEnd; i++)
{
matrix[rowEnd][i] = num++;
}
rowEnd--;
// 向上填充
if (colStart <= colEnd)
{
for (int i = rowEnd; i >= rowStart; i--)
{
matrix[i][colEnd] = num++;
}
colEnd--;
}
// 向左填充
if (rowStart <= rowEnd)
{
for (int i = colEnd; i >= colStart; i--)
...
登录后发布评论
暂无评论,来抢沙发