# 4ms C++ ,Easy to Understand!

• ``````vector<vector<int> > Solution::generateMatrix(int x)
{
vector<vector<int> > my2DVector(x,vector<int>(x,0));
int number = 1;
int m = my2DVector.size();
for(int i=0;i<=m/2;i++)
{
for(int j=i;j<m-i;j++) // left -->right
my2DVector[i][j] = number++;
for(int j=i+1;j<m-i;j++) // up --> down
my2DVector[j][m-i-1] = number++;
for(int j=m-i-2;j>=i;j--) // right --> left
my2DVector[m-i-1][j] = number++;
for(int j=m-i-2;j>=i+1;j--) // down --> up
my2DVector[j][i] = number++;
}
return my2DVector;
}``````

• vector<vector<int>> generateMatrix(int n)
{
vector<int> v1;
vector<vector<int>> p;
v1.resize(n);
int i = 0;
int j = 0;
for (i=0;i<n;i++)p.push_back(v1);
int k = n;
int start = 0;
int first = 1;
while (k>0)
{
//i不变，j++;
for (j=start;j<start+k;j++)
{
p[start][j]=first;
first++;
}
j=start+k-1;
for (i=start+1;i<start+1+k-1;i++)
{
p[i][j]=first;
first++;
}
i = start+k-1;
//i不变，j--
for (j=start+k-2;j>=start;j--)
{
p[i][j]=first;
first++;
}
j=start;
for (i=start+k-2;i>=start+1;i--)
{
p[i][j]=first;
first++;
}
k=k-2;
start=start++;
}
return p;
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.