public class Solution {
public int[,] GenerateMatrix(int n) {
int[,] mt = new int[n,n];
int end = n*n, num = 1, i = 0;
while(num < end){
int edge = n  1  i, j = i;
while (j < edge) mt[i, j++] = num++;
while (i < edge) mt[i++, j] = num++;
edge = n  1  edge;
while (j > edge) mt[i, j] = num++;
while (i > edge) mt[i, j] = num++;
i++;
}
if (n % 2 == 1) mt[i,i] = num;
return mt;
}
}
Simple and easy to understand C# solution


public int[,] GenerateMatrix(int n) { int[,] mt = new int[n,n]; int end = n*n, num = 1, i = 0; while(num < end){ int edge = n  1  i, j = i; while (j < edge) mt[i, j++] = num++; while (i < edge) mt[i++, j] = num++; edge = n  1  edge; while (j > edge) mt[i, j] = num++; while (i > edge) mt[i, j] = num++; i++; } if (n % 2 == 1) mt[i,i] = num; return mt; }