点击打开链接
//蛇形数组,vector<vector<int>> res 赋值,先赋值给一个vector<int>a. a再赋值给res
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<vector>
using namespace std;
class Solution {
public:
vector< vector<int> > generateMatrix(int n) {
int tot=1,i=0,j=0,Arr[n+5][n+5];
vector< vector<int> > res;
memset(Arr, 0, sizeof(Arr));
Arr[0][0]=tot; tot+=1;
i=0,j=0;
while(tot<=n*n){
while(j+1<n&&!Arr[i][j+1]){
j+=1;
Arr[i][j]=tot;
tot+=1;
}
while(i+1<n&&!Arr[i+1][j]){
i+=1;
Arr[i][j]=tot;
tot+=1;
}
while(j-1>=0&&!Arr[i][j-1]){
j-=1;
Arr[i][j]=tot;
tot+=1;
}
while(i-1>=0&&!Arr[i-1][j]){
i-=1;
Arr[i][j]=tot;
tot+=1;
}
}
vector<int>a;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
a.push_back(Arr[i][j]);
}
res.push_back(a);
a.clear();
}
/*
for(i=0;i<res.size();i++){
for(j=0;j<res.size();j++){
cout<<res[i][j]<<" ";
}
cout<<endl;
}
*/
return res;
}
};
int main()
{
Solution temple;
temple.generateMatrix(4);
return 0;
}