class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> matrix(n,vector<int>(n));
if(n==0) return matrix;
leftPos = 0;
rightPos = matrix[0].size()-1;
topPos = 0;
bottomPos = matrix.size()-1;
value = 1;
goWider(matrix, true);
return matrix;
}
void goWider(vector<vector<int>> &matrix, bool direct)
{
if(direct)
{
for(int i = leftPos; i<= rightPos; i++)
{
matrix[topPos][i] = value++;
}
topPos++;
if(topPos > bottomPos) return;
goDeeper(matrix, true);
}
else
{
for(int i = rightPos; i>= leftPos; i--)
{
matrix[bottomPos][i]=value++;
}
bottomPos--;
if(topPos > bottomPos) return;
goDeeper(matrix, false);
}
}
void goDeeper(vector<vector<int>> &matrix, bool direct)
{
if(direct)
{
for(int i = topPos; i<= bottomPos; i++)
{
matrix[i][rightPos]=value++;
}
rightPos--;
if(leftPos > rightPos) return;
goWider(matrix, false);
}
else
{
for(int i = bottomPos; i>= topPos; i--)
{
matrix[i][leftPos] = value++;
}
leftPos++;
if(leftPos > rightPos) return;
goWider(matrix, true);
}
}
private:
int leftPos;
int rightPos;
int topPos;
int bottomPos;
int value;
};