# 问题

[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Given a positive integer n, generate a square matrix filled with elements from 1 to n^2n2 in spiral order.

Input: 3

Output: [
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

# 示例

```public class Program {

public static void Main(string[] args) {
var n = 3;

var res = GenerateMatrix(n);
ShowArray(res);

}

private static void ShowArray(int[,] matrix) {
for(var i = 0; i < matrix.GetLength(0); i++) {
for(var j = 0; j < matrix.GetLength(1); j++) {
Console.Write(\$"{matrix[i, j]} ");
}
Console.WriteLine();
}
}

public static int[,] GenerateMatrix(int n) {
var list = new List<int>();
var max = (int)Math.Ceiling(n / 2d);
var matrix = new int[n, n];
var count = 0;
Spiral(matrix, 0, n, n, max, ref count);
return matrix;
}

private static void Spiral(int[,] matrix,
int level,
int m,
int n,
int max,
ref int count) {
if(level >= max) return;
//顶端
for(var j = level; j < n - level; j++) {
matrix[level, j] = ++count;
}
//右端
for(var i = level + 1; i < m - level - 1; i++) {
matrix[i, n - level - 1] = ++count;
}
//底端
if(level != m - level - 1) {
for(var j = n - level - 1; j >= level; j--) {
matrix[m - level - 1, j] = ++count;
}
}
//左端
if(level != n - level - 1) {
for(var i = m - level - 2; i >= level + 1; i--) {
matrix[i, level] = ++count;
}
}
Spiral(matrix, ++level, m, n, max, ref count);
}

}
```

```1 2 3
8 9 4
7 6 5
```