Simplest C++ solution. It took me 2 hours to derive this!


#1

vector<vector > Solution::generateMatrix(int A)
{
vector<vector> v(A,vector(A));

int k=0;
int n=A-1;
while(k<=A/2)
{
    for(int i=k;i<n-k;i++)
    {
        v[k][i] = (int)(A-k)*(4*k + 0) - 1*k + i + 1 ;
        v[i][n-k] = (int)(A-k)*(4*k + 1) - 2*k + i ;
        v[n-k][n-i] = (int)(A-k)*(4*k + 2) - 3*k + i - 1 ;
        v[n-i][k] = (int)(A-k)*(4*k + 3) - 4*k + i - 2 ;
    }
    k=k+1;
}
if(A%2==1) v[(int)A/2][(int)A/2]=(int) pow(A,2);
if(A==1) v[0][0]=1;
return v;

}