# C#LeetCode刷题之#54-螺旋矩阵（Spiral Matrix）

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

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

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

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

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

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]

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

public class Program {

public static void Main(string[] args) {
var matrix = new int[,] {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8 ,9, 10 },
{ 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20 },
{ 21, 22, 23, 24, 25 }
};

var res = SpiralOrder(matrix);
ShowArray(res);

}

private static void ShowArray(IList<int> list) {
foreach(var num in list) {
Console.Write(\$"{num} ");
}
Console.WriteLine();
}

public static IList<int> SpiralOrder(int[,] matrix) {
var list = new List<int>();
var m = matrix.GetLength(0);
var n = matrix.GetLength(1);
var max = (int)Math.Ceiling(Math.Min(m, n) / 2d);
Spiral(matrix, 0, m, n, max, ref list);
return list;
}

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

}

1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13