Easy to understand O(n2)


#1

vector<vector > Solution::generateMatrix(int A)
{
vector<vector> res(A, vector(A, 0));
int row_min=0, row_max=A-1, col_min=0, col_max=A-1, dir=0, row=0, col=0, i=1;
while(i<=A*A)
{
if(dir==0&&col<=col_max)
{
res[row][col]=i;
col++;
i++;
}
else if(dir==0&&col>col_max)
{
row+=1;
row_min+=1;
col=col_max;
dir=1;
}
if(dir==1&&row<=col_max)
{
res[row][col]=i;
row++;
i++;
}
else if(dir==1&&row>row_max)
{
col-=1;
col_max-=1;
row=row_max;
dir=2;
}
if(dir==2&&col>=col_min)
{
res[row][col]=i;
col–;
i++;
}
else if(dir==2&&col<col_min)
{
row-=1;
row_max-=1;
col=col_min;
dir=3;
}
if(dir==3&&row>=row_min)
{
res[row][col]=i;
row–;
i++;
}
else if(dir==3&&row<row_min)
{
col+=1;
col_min+=1;
row=row_min;
dir=0;
}
}
return res;
}


#3

It’s clearly mentioned that this solution is O(n ^ 2).