forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0054-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
publicclassSolution{
publicIList<int>SpiralOrder(int[][]matrix){
List<int>result=newList<int>();
inttop=0;
intleft=0;
intright=matrix[0].Length-1;
intbottom=matrix.Length-1;
while(true)
{
//Left to Right
for(inti=left;i<=right;i++)
{
result.Add(matrix[top][i]);
}
top++;
if(left>right||top>bottom)break;
//Top to Bottom
for(inti=top;i<=bottom;i++)
{
result.Add(matrix[i][right]);
}
right--;
if(left>right||top>bottom)break;
//Right to Left
for(inti=right;i>=left;i--)
{
result.Add(matrix[bottom][i]);
}
bottom--;
if(left>right||top>bottom)break;
//Bottom to Top
for(inti=bottom;i>=top;i--)
{
result.Add(matrix[i][left]);
}
left++;
if(left>right||top>bottom)break;
}//Repeat
returnresult;
}
}