forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0054-spiral-matrix.cs
45 lines (41 loc) · 1.33 KB
/
0054-spiral-matrix.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
public class Solution {
public IList<int> SpiralOrder(int[][] matrix) {
List<int> result = new List<int>();
int top = 0;
int left = 0;
int right = matrix[0].Length - 1;
int bottom = matrix.Length - 1;
while (true)
{
//Left to Right
for (int i = left; i <= right; i++)
{
result.Add(matrix[top][i]);
}
top++;
if (left > right || top > bottom) break;
//Top to Bottom
for (int i = top; i <= bottom; i++)
{
result.Add(matrix[i][right]);
}
right--;
if (left > right || top > bottom) break;
//Right to Left
for (int i = right; i >= left; i--)
{
result.Add(matrix[bottom][i]);
}
bottom--;
if (left > right || top > bottom) break;
//Bottom to Top
for (int i = bottom; i >= top; i--)
{
result.Add(matrix[i][left]);
}
left++;
if (left > right || top > bottom) break;
}//Repeat
return result;
}
}