public class Solution { public int[,] GenerateMatrix(int n) { var matrix = new int[n,n]; var row = n % 2 == 0 ? n / 2 : (n+1) / 2; var count = 1; for(var cycle = 0;cycle < row; cycle++){ // left to right for(var col = cycle;col < n - cycle - 1; col++){ matrix[cycle,col] = count ++; } // right to bottom for(var r = cycle ; r < n - cycle; r++){ matrix[r, n - cycle - 1] = count ++; } // bottom to left for(var col = n - cycle - 2;col >= cycle; col --){ matrix[n-cycle-1,col] = count ++; } // left to top for(var r = n - cycle - 2;r > cycle; r --){ matrix[r,cycle] = count ++; } } return matrix; } }