Concise solution using Four pointers (top,bottom,left,right)


#1

vector<vector > Solution::generateMatrix(int A) {
vector<vector>ans(A,vector(A));
int k=1;
int l=0;int t=0;int r=A-1;int b=A-1;
int ptr=1;
while(l<=r && t<=b){

    if(ptr==1){    //Check whether we have to traverse top
        for(int j=l;j<=r;j++)
        ans[t][j]=k++;
        t++;
    }
    if(ptr==2){   //Check whether we have to traverse right
        for(int j=t;j<=b;j++)
        ans[j][r]=k++;
        r--;
    }
    if(ptr==3){    //Check whether we have to traverse bottom
        for(int j=r;j>=l;j--)
        ans[b][j]=k++;
        b--;
    }
    if(ptr==0){      //Check whether we have to traverse left
        for(int j=b;j>=t;j--)
        ans[j][l]=k++;
        l++;
    }
    ptr++;
    ptr=ptr%4;
}
return ans;

}