-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0059-Spiral-matrix-II.cs
More file actions
61 lines (49 loc) · 1.38 KB
/
0059-Spiral-matrix-II.cs
File metadata and controls
61 lines (49 loc) · 1.38 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0059.Spiral_matrix_II
{
public class _0059_Spiral_matrix_II
{
public int[][] GenerateMatrix(int n)
{
int num = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int[][] res = new int[n][];
for (int i = 0; i < n; i++)
res[i] = new int[n];
while (left <= right && top <= bottom)
{
// left to right
for (int i = left; i <= right; i++)
{
res[top][i] = num;
num++;
}
top++;
// top to bottom
for (int j = top; j <= bottom; j++)
{
res[j][right] = num;
num++;
}
right--;
// right to left
for (int i = right; i >= left; i--)
{
res[bottom][i] = num;
num++;
}
bottom--;
// bottom to top
for (int j = bottom; j >= top; j--)
{
res[j][left] = num;
num++;
}
left++;
}
return res;
}
}
}