Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fe47035

Browse files
ADD Spiral-Matrix problem #72
1 parent 0d5480e commit fe47035

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

‎Medium/spiral-matrix.cs‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
public class Solution
2+
{
3+
public static IList<int> SpiralOrder(int[][] matrix)
4+
{
5+
if (matrix is null || matrix.Length == 0)
6+
{
7+
return [];
8+
}
9+
10+
IList<int> result = new List<int>();
11+
int top = 0;
12+
int bottom = matrix.Length - 1;
13+
int left = 0;
14+
int right = matrix[0].Length - 1;
15+
16+
while (true)
17+
{
18+
//Left to Right
19+
for (int i = left; i <= right; i++)
20+
{
21+
result.Add(matrix[top][i]);
22+
}
23+
top++;
24+
if (left > right || top > bottom) break;
25+
26+
//Top to Bottom
27+
for (int i = top; i <= bottom; i++)
28+
{
29+
result.Add(matrix[i][right]);
30+
}
31+
right--;
32+
if (left > right || top > bottom) break;
33+
34+
//Right to Left
35+
for (int i = right; i >= left; i--)
36+
{
37+
result.Add(matrix[bottom][i]);
38+
}
39+
bottom--;
40+
if (left > right || top > bottom) break;
41+
42+
//Bottom to Top
43+
for (int i = bottom; i >= top; i--)
44+
{
45+
result.Add(matrix[i][left]);
46+
}
47+
left++;
48+
if (left > right || top > bottom) break;
49+
}
50+
51+
return result;
52+
}
53+
54+
private static void _PrintMatrix(int[][] matrix)
55+
{
56+
foreach (var row in matrix)
57+
{
58+
Console.WriteLine(string.Join(" ", row));
59+
}
60+
Console.WriteLine();
61+
}
62+
63+
static void Main()
64+
{
65+
int[][] matrix =
66+
[
67+
[1,2,3,4],
68+
[5,6,7,8],
69+
[9,10,11,12]
70+
];
71+
72+
IList<int> list = SpiralOrder(matrix);
73+
74+
Console.WriteLine("Original matrix:");
75+
_PrintMatrix(matrix);
76+
77+
78+
Console.WriteLine("Matrix after rotation:");
79+
80+
Console.WriteLine(string.Join(", ", list));
81+
}
82+
}
83+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /