vector<vector<int>> generateMatrix(int n) {
int loops = n >> 1, j, cnt = 1;
vector<vector<int>> m(n, std::vector<int>(n));
for (int i = 0; i < loops; i++){
for (j = i; j < n  i; j++)
m[i][j] = cnt++;
for (j = i + 1; j < n  i; j++)
m[j][n  i  1] = cnt++;
for (j = n  i  2; j >= i; j)
m[n  i  1][j] = cnt++;
for (j = n  i  2; j > i; j)
m[j][i] = cnt++;
}
if (n % 2 == 1) m[loops][loops] = cnt;
return m;
}
A mathematical approach


def generateMatrix(n): """ :type n: int :rtype: List[List[int]] """ loops = n >> 1; cnt = 1 m = [[0 for k in range(n)] for k in range(n)] for i in xrange(loops): for j in xrange(i, ni): m[i][j] = cnt; cnt += 1 for j in xrange(i+1, ni ): m[j][ni1] = cnt; cnt += 1 for j in xrange(ni2, i1, 1): m[ni1][j] = cnt; cnt += 1 for j in xrange(ni2, i, 1): m[j][i] = cnt; cnt += 1 if n % 2 == 1: m[loops][loops] = cnt return m