-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path054-SpiralMatrix.cs
47 lines (38 loc) · 1.42 KB
/
054-SpiralMatrix.cs
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//-----------------------------------------------------------------------------
// Runtime: 476ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _054_SpiralMatrix
{
public IList<int> SpiralOrder(int[,] matrix)
{
var result = new List<int>();
var rowLength = matrix.GetLength(0);
var colLength = matrix.GetLength(1);
int circle = 0, i, lastCol, lastRow;
while (true)
{
lastCol = colLength - circle - 1;
lastRow = rowLength - circle - 1;
for (i = circle; i <= lastCol; i++)
result.Add(matrix[circle, i]);
if (result.Count == matrix.Length) { break; }
for (i = circle + 1; i < lastRow; i++)
result.Add(matrix[i, lastCol]);
if (result.Count == matrix.Length) { break; }
for (i = lastCol; i >= circle; i--)
result.Add(matrix[lastRow, i]);
if (result.Count == matrix.Length) { break; }
for (i = lastRow - 1; i > circle; i--)
result.Add(matrix[i, circle]);
if (result.Count == matrix.Length) { break; }
circle++;
}
return result;
}
}
}