Leetcode Daily Problem
59. Spiral Matrix II
In the very last question, we have done a question where we have to print a 2D matrix in spiral form and in this question, we have to insert values into that 2D matrix from i to n^2.
The approach for this problem would be the same as in the previous question, we will make a 2d vector with all values 0 and the same as in the previous question we will insert values into the array.
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> vec(n,vector<int> (n,0));
int k=1;
int srow=0;
int erow=n-1;
int scol=0;
int ecol=n-1;
while(srow<=erow && scol<=ecol)
{
for(int j=scol;j<=ecol;j++)
{
vec[srow][j]=k;
k++;
}
for(int j=srow+1;j<=erow;j++)
{
vec[j][ecol]=k;
k++;
}
for(int j=ecol-1;j>=scol;j--)
{
if(srow==erow)
{
break;
}
vec[erow][j]=k;
k++;
}
for(int j=erow-1;j>=srow+1;j--)
{
if(scol==ecol)
{
break;
}
vec[j][scol]=k;
k++;
}
srow++;
scol++;
erow--;
ecol--;
}
return vec;
}