Easy to understand C++ solution. Simple if-else statements


#1

vector<vector > Solution::generateMatrix(int n)
{
vector<vector>a;
vectortemp;
for(int i=0;i<n;i++)
{
temp.push_back(-1);
}
for(int i=0;i<n;i++)
{
a.push_back(temp);
}
int start=0;
int end=n*n;
int end_row=n-1;
int end_col=n-1;
int start_row=0;
int start_col=0;
int flag=1;
//just making it print how you would have done with your hand.
while(start!=end)
{
if(flag==1)
{
for(int i=start_col;i<=end_col;i++)
{
start++;
a[start_row][i]=start;
}
start_row+=1;
flag=2;
continue;
}
if(flag==2)
{
for(int i=start_row;i<=end_row;i++)
{
start++;
a[i][end_col]=start;
}
end_col-=1;
flag=3;
continue;
}
if(flag==3)
{
for(int i=end_col;i>=start_col;i–)
{
start++;
a[end_row][i]=start;
}
end_row-=1;
flag=4;
continue;
}
if(flag==4)
{
for(int i=end_row;i>=start_row;i–)
{
start++;
a[i][start_col]=start;
}
start_col+=1;
flag=1;;
continue;
}
}
return a;
}