Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int tot=1,x=0,y=0;
vector<vector<int>> v(n,vector<int>(n));
if(n==1){
v[0][0]=1;
return v;
}
while(tot<n*n){
v[0][0]=1;
while(y+1<n&&!v[x][y+1]){
v[x][++y]=++tot;
}
while(x+1<n&&!v[x+1][y]){
v[++x][y]=++tot;
}
while(y-1>=0&&!v[x][y-1]){
v[x][--y]=++tot;
}
while(x-1>=0&&!v[x-1][y]){
v[--x][y]=++tot;
}
}
return v;
}
};

本文介绍了一个算法,该算法接收一个整数 n,并生成一个 n x n 的矩阵,矩阵中的元素从1到n²,按螺旋顺序填充。例如,当 n 为3时,将返回如下矩阵:[[1,2,3],[8,9,4],[7,6,5]]。文章通过一个具体的 C++ 类实现展示了如何实现这一功能。

被折叠的 条评论
为什么被折叠?



