Easy To Understand C++ solution O(A*A)


#1

vector<vector > Solution::generateMatrix(int A) {

vector<vector<int>> vec( A , vector<int> (A, 0));

 int srow=0,scol=0,erow=A-1,ecol=A-1;
 int val=1;
while(srow<=erow&&scol<=ecol){
    //up row
    for(int i=scol;i<=ecol;i++){
        vec[srow][i]=val;
        val++;
    }
    srow++;
    //right col
    for(int i=srow;i<=erow;i++){
        vec[i][ecol]=val;
        val++;
    }
    ecol--;
      //down row
    if(srow<=erow){
       for(int i=ecol;i>=scol;i--){
           vec[erow][i]=val;
           val++;
       }
       erow--; 
    }  
    //left col
    if(scol<=ecol){
     for(int i=erow;i>=srow;i--){
           vec[i][scol]=val;
           val++;
     }
     scol++;   
    }
}

return vec;

}